简体   繁体   中英

React 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 are blowing up with TypeError: 'undefined' is not an object (evaluating 'this.props.field.errors.length') , shouldn't my default props give it a default value? Initially, my field prop is an empty object.

Initially, my field prop is an empty object.

Default props are only used if no value is passed for the prop. It is is shallow merge, not a deep merge.

From the docs (emphasis mine):

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

You can't mix isRequire with defaultProps. If you give isRequired to field the defaultProps will be ignored.

This should work:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM