#1
你好。
我有代码:
class Component extends React.Component {
render() {
this.props.nested.prop = this.props.parse.nested.prop;
return <div>Component</div>;
}
componentDidMount() {
console.log(this.props.nested.prop);
}
}
Component.defaultProps = {
nested: {
prop: "default",
},
};
const obj1 = {
nested: {
prop: "obj1",
},
};
const obj2 = {
nested: {
prop: "obj2",
},
};
class Application extends React.Component {
render() {
return (
<div>
<Component parse={obj1} />
<Component parse={obj2} />
</div>
);
}
}
React.render(<Application />, document.getElementById("app"));
// console output:
// "obj2"
// "obj2"
为什么我得到 2 个独立组件的 1 个变量引用,而不是每个组件的 2 个nested.prop 实例?
为什么 this.props 在安装后只保存组件所有实例的最后设置值?这是正常行为吗?
我认为正确的行为是针对不同的实例具有不同的属性值。
附:我已经测试过这段代码here http://codepen.io/voronar/pen/mPwebK.
#2
jimfb https://github.com/jimfb已回答:"You are mutating the default prop that was passed in. The line this.props.nested.prop = this.props.parse.nested.prop; is illegal."
我的下一个问题:How to pass nested properties without a manual mutation of props?
例如:
Component.defaultProps = {
nested: {
prop1: "default",
prop2: "default",
},
};
const props = {
nested: {
prop1: "value",
},
};
let component = <Component {...props} />;
上面的代码指南 JSX 扩展属性功能只是覆盖 props.nested 并且我丢失了默认的嵌套属性。但这不是我需要的。
如何在JSX扩展属性解析阶段实现嵌套对象的递归遍历?
或者这种情况有一些有用的模式吗?