我正在尝试使用对象文字设置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'));
最佳答案
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/