道具阵列需要深层复制吗?

问题描述 投票:0回答:1

我刚刚开始进入React和JS,我正在尝试学习如何以及何时复制。道具是不可变的,但出于某种原因,当从道具中分配数组时,我没有遇到任何问题。另外,我知道复制数组很浅,但是当我将1个数组分配给状态1中的两个变量时,不会改变另一个。我错过了什么?

javascript reactjs
1个回答
0
投票

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的值不会更改bc的值。如果你想更新bc的状态,你需要单独完成。

© www.soinside.com 2019 - 2024. All rights reserved.