reactjs – React.Component.defaultProps对象被覆盖,没有合并?

我正在尝试使用对象文字设置defaultProp,但过了一段时间后我意识到React类构造函数没有将认道具与应用的道具合并,所以我最终得到了defaultProps文字中任何属性的未定义值尚未包含在应用道具中.有没有办法合并认道具和应用道具,还是我需要将我的对象分解成几个道具?
class Test extends React.Component {
  constructor(props) {
    super(props);

    //props.test is only {one: false}
    //props.test.two is undefined

  }
  render() {
    return (<div>render</div>)
  }
}

Test.defaultProps = {
  test:  {
    one: true,two: true
  }
}


ReactDOM.render(<Test test={{'one': false}}/>,document.getElementById('#test'));

http://codepen.io/adjavaherian/pen/oYNPLz

React只对认道具和实际道具进行浅层合并,即嵌套的认道具被覆盖而不是合并.这是设计的.

有关更多背景和推理,请参阅this React issue,为什么会出现这种情况和可能的解决方法

aside from the potential perf issues here. one issue with this is how do you handle nested complex structures like arrays? concatenation? Union? what about an array of objects? deep object merging can lead to unexpected behavIoUr,which is why often implementations allow you to specify a merge strategy such as _. merge. I’m not sure how you would do that in prop type declaration.

相关文章

react 中的高阶组件主要是对于 hooks 之前的类组件来说的,如...
我们上一节了解了组件的更新机制,但是只是停留在表层上,例...
我们上一节了解了 react 的虚拟 dom 的格式,如何把虚拟 dom...
react 本身提供了克隆组件的方法,但是平时开发中可能很少使...
mobx 是一个简单可扩展的状态管理库,中文官网链接。小编在接...
我们在平常的开发中不可避免的会有很多列表渲染逻辑,在 pc ...