Responsive defaultProps not working

I'm probably doing something stupid, but I can't get defaultProps to work.

export default class MyClass extends Component{ static propTypes = { name: React.PropTypes.string.isRequired, field: React.PropTypes.object.isRequired } static defaultProps = { field: { value: '', errors: [] } } render() { // blah blah } } 

I have code that relies on this.props.field.value and this.props.field.errors.length , and all my tests explode with TypeError: 'undefined' is not an object (evaluating 'this.props.field.errors.length') , should my default details not give a default value? Initially, my field prop is an empty object.

+10
source share
2 answers

Initially, my field prop is an empty object.

Default details are used only if the value is not passed to the support. This is a shallow merger, not a deep merger.

From the docs (my highlight):

The result of getDefaultProps() will be cached and used to ensure that this.props.value will matter if it was not specified by the parent component .

+20
source

You cannot mix isRequire with defaultProps. If you give isRequired for the field, defaultProps will be ignored.

This should work:

 static propTypes = { name: React.PropTypes.string.isRequired, field: React.PropTypes.object }; static defaultProps = { field: { value: '', errors: [] } }; 
0
source

Source: https://habr.com/ru/post/1234203/


All Articles