问题
Code here: https://codesandbox.io/s/github/nieroda/js_err
In function endTurn
console.log(`GameBoard Before`)
console.log(gameBoardCopy)
gameBoardCopy[currentRow][4] = { numColorMatch: 2, numExactMatch: 2 }
console.log(`GameBoard After`)
console.log(gameBoardCopy)
See Console Output
Before:
5: Array(5)
0: "BlueViolet"
1: "BlueViolet"
2: "BlueViolet"
3: "BlueViolet"
4: {numColorMatch: 0, numExactMatch: 0}
After
5: Array(5)
0: "BlueViolet"
1: "BlueViolet"
2: "BlueViolet"
3: "BlueViolet"
4: {numColorMatch: 0, numExactMatch: 0}
I can't figure out why it's not working?
回答1:
Your data is updating, but it is getting mutated elsewhere in the code, and the console.log
isn't quite immediate enough (especially with the code sandbox wrapper around console.log
). So in order to get around that do one of the following:
JSON.stringify
your data before passing it toconsole.log
. This will freeze the data into a string.- Deep copy your data structure before passing to
console.log
. (Problem is that there is no built-in deep copy for JS) - Use a debugger and set a breakpoint after the log, either with the debugger console or with the
debugger
statement. (Usuallydebugger
statements are ignored if the debugger console is hidden, so make sure that is up). This will interrupt the normal flow and force the log to flush, giving you more accurate data.
That answers your question, but not your problem, which is that you are mutating things you don't expect to. That can be solved by making sure you are first (deep) copying everything you are mutating, not using mutation (libraries like Immutable.js can help there), or using something like MobX which allows you to mutate things and then subscribe to those mutation events.
来源:https://stackoverflow.com/questions/54935972/react-javascript-assignment-not-updating-object