关于我之前的问题(代码仍然给我带来麻烦):React: Javascript assignment not updating object
代码在这里https://codesandbox.io/s/github/nieroda/js_err
你可以在第2行看到我有的对象。尽管打印输出不同(如下所示),但是在2和5之间没有发生突变,这使我相信代码正在按顺序执行。
codeBreaker.js:108
1. console.log("BEFORE")
2. console.log(gameBoardCopy[currentRow])
3. console.log("END")
let copy = this.state.gameBoard[currentRow].slice()
4. console.log("Copy Start")
5. console.log(copy)
6. console.log("Before Assignment")
copy[4] = { numColorMatch: 2, numExactMatch: 2 }
7. console.log("After Assignment")
8. console.log(copy)
9. console.log("copy end")
看着输出
2.
0: "BlueViolet"
1: "BlueViolet"
2: "BlueViolet"
3: "BlueViolet"
4: {numColorMatch: 0, numExactMatch: 0}
5.
0: "BlueViolet"
1: "BlueViolet"
2: "BlueViolet"
3: "BlueViolet"
4: {numColorMatch: 2, numExactMatch: 2}
0: "BlueViolet"
1: "BlueViolet"
2: "BlueViolet"
3: "BlueViolet"
4: {numColorMatch: 2, numExactMatch: 2}
我无法弄清楚造成这种情况的原因,提示赞赏。谢谢
console.log
实际上是一种异步方法,这很可能是为什么你看到执行“出现”乱序。每当你console.log
一个对象,请确保console.log(JSON.stringify(JSON.parse(value)));
。
查看执行顺序及其值的更好方法是添加debugger
语句。尝试在第5步之上添加debugger;
并遍历代码以查看实际值是什么。我会想象价值会像你期望的那样。如果没有,使用调试器逐步完成该过程将告诉您原因。
看起来你无意中改变了组件的状态。你没有在这里复制对象。 Javascript对象通过引用传递,这意味着当您直接将此类对象分配给另一个变量时,它们都将修改相同的数据。
代替:
let copy = this.state.gameBoard[currentRow].slice()
呼叫:
let copy = Object.assign({}, this.state.gameBoard[currentRow]);
如果您打算更新组件的状态,则应调用the.setState({obj})
。
如果你必须深度克隆一个对象,我建议使用lodash或underscore 的深拷贝函数(或者创建你自己的:Objects in JS: deep copy)。
希望这可以帮助,