【发布时间】:2016-07-15 21:39:03
【问题描述】:
#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。
#2
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 传播属性解析阶段如何实现嵌套对象的递归遍历?
或者这种情况有一些有用的模式吗?
【问题讨论】:
-
请在这里提出一个完全合格的问题,因为链接可能会失效。
-
以下是如何在 SO 上提出好问题的提示:stackoverflow.com/help/how-to-ask
-
“如何传递嵌套属性”
foo(a.nested.property)? -
好的。稍后我将在家中使用我的电脑。
-
我不明白你想用你的代码实现什么。为什么要尝试将道具存储在其他道具中?以后你想怎么处理?
标签: javascript reactjs jsx