javascript 反应 defaultProps 不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33262714/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 16:17:22  来源:igfitidea点击:

React defaultProps not working

javascriptreactjs

提问by Lee

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

我可能正在做一些愚蠢的事情,但我无法让 defaultProps 工作。

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.valueand this.props.field.errors.lengthand 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 fieldprop is an empty object.

我有依赖于this.props.field.valueand 的代码,this.props.field.errors.length而且我所有的测试都被炸毁了TypeError: 'undefined' is not an object (evaluating 'this.props.field.errors.length'),我的默认道具不应该给它一个默认值吗?最初,我的field道具是一个空对象。

回答by Felix Kling

Initially, my fieldprop is an empty object.

最初,我的field道具是一个空对象。

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.valuewill have a value if it was not specified by the parent component.

的结果getDefaultProps()将被缓存并用于确保如果父组件没有指定它this.props.value会有一个值。

回答by Catalina

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

您不能将 isRequire 与 defaultProps 混合使用。如果你给 isRequired 字段,defaultProps 将被忽略。

This should work:

这应该有效:

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