reactjs - React.Component.defaultProps 对象被覆盖,而不是合并?

标签 reactjs ecmascript-6

我正在尝试使用对象文字设置defaultProp,但一段时间后我意识到React类构造函数没有将默认 Prop 与应用的 Prop 合并,因此我最终得到了未定义的值尚未包含在应用的 props 中的 defaultProps 文字。有没有办法合并默认 Prop 和应用 Prop ,或者我是否需要将我的对象分解为多个 Prop ?

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 只对默认 props 和实际 props 进行浅层合并,即嵌套的默认 props 被覆盖而不是合并。这是设计使然。

参见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.

关于reactjs - React.Component.defaultProps 对象被覆盖,而不是合并?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40428847/

相关文章:

javascript - 如何修复 React Redux 和 React Hook useEffect 缺少依赖项 : 'dispatch'

reactjs - 使用 pm2 在服务器上运行 React 构建

javascript - 如何在使用 React 时将表格行转换为列

Angular 5.0 的变更检测策略 VS React 的变更检测策略

javascript - EcmaScript语法中的什么是[ yield ,等待,中,返回]

reactjs - 如何解决违反 ESLint 规则 'react/no-unescaped-entitie' 的问题?

javascript - 导入 moment.js 部分或函数

javascript - 函数的默认参数值、解构赋值

javascript - 在另一个函数中传递函数参数

javascript - 在 es6 中调用另一个类的函数