なぜ1つの状態を変更すると、他のすべての変更?これを防ぐ方法は?関数内で、私はdata
で二つの状態を作成し、子小道具に至るまで、これらの二つの状態を渡す受け取っ:関数は1つではなく2つの状態を変更します
親:
...
// getInitialState: foo and bar
...
// An ajax calls this with an array data
// My two states: foo and bar
getData(data){
this.setState({ foo: data, bar: data });
}
// Render
<Child myFoo={this.state.foo} myBar={this.state.bar} />
が子供:
getInitialState(){
return{
childFoo: this.props.myFoo,
childBar: this.props.myBar
}
},
valueChange(i, e){
// i is passed in as a number when this function is called.
// to show how "i" is passed in is not important
e.preventDefault();
var obj = this.state.childFoo;
var num = obj.find(p => i === p.id);
// This changes both of my states! Why?
num.unit_amount = e.target.value;
}
でしたが誰かが理由を説明する理由childBar
も変更されますか?私は1つを変えて、もう一方を使って値を比較する必要があります。
子供の例は本当に明確ではありませんが、あなたはそれをsemplifyできますか? childBarとは何ですか? – Carlo
childBarは、getInitialStateでのみ設定するため、変更しないでください。それはあなたがそれをどこか別の場所に更新した場合、または子コンポーネントのマウント・アンマウントを行う場合にのみ変更される可能性があります(子供の代わりにnullまたはundefinedを返す場合) – degr
@Carloそれは明らかです。 'childBar'は' childFoo'と同じです。これらの2人は、元の状態からデータを取得します。 – Sylar