#1スプレッド属性でネストされたプロパティを正しく渡す方法(JSX)
こんにちは。私は2つの別々のコンポーネントの代わりに、すべてのコンポーネントのためのnested.propの2 instansesのための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"
: 私は、コードを持っていますか? なぜthis.propsはマウント後にコンポーネントのすべてのinstansに対して最後に設定された値だけを保存するのですか?それは正常な行動ですか? 私は正しい動作が異なるinstansesの異なるプロパティ値を持っていると思います。
P.S.私はこのコードhereをテストしました。
#2
jimfb annsweredされています: "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スプレッド属性解析の段階で、ネストされたオブジェクトの再帰的なトラバースを実装するのはどうですか?
このケースにはいくつかの有用なパターンがありますか?
は完全修飾を依頼してください大幅に列挙されている多くの問題を上昇リンクが死ぬ可能性があるのでここで質問してください。 – Neal
ここで、SOに関する良い質問をするヒントを教えてください:http://stackoverflow.com/help/how-to-ask – migg
* "ネストされたプロパティを渡す方法" * 'foo(a.nested.property)'? –