我刚刚开始进入React和JS,我正在尝试学习如何以及何时复制。道具是不可变的,但出于某种原因,当从道具中分配数组时,我没有遇到任何问题。另外,我知道复制数组很浅,但是当我将1个数组分配给状态1中的两个变量时,不会改变另一个。我错过了什么?
but when I assign 1 array to two variables in the state 1 does not change the other
从同一个数组创建两个javascript变量不会使它们绑在一起。例如:
this.state = { a: 'foo',
b: 'foo2',
c: 'foo3'
}
console.log('This is b: '+this.state.b); // => 'This is b: foo2'
console.log('This is c: '+this.state.c); // => 'This is c: foo3'
this.setState({ b: 'bar' })
console.log('This is new b: '+b); // => 'This is new b: bar'
console.log('c doesnt change: '+c); // => 'c doesnt change: foo3'
此外,更改a
的值不会更改b
和c
的值。如果你想更新b
和c
的状态,你需要单独完成。