我找不到任何类似的问题,我不知道那里会发生什么(也许可能是愚蠢的事情),但我还没有找到任何关于可能发生的事情的线索。
我有这个数组:
const superVillains = [
{ value: '1', label: 'Thanos' },
{ value: '2', label: 'The Joker' },
{ value: '3', label: 'Ultron', disabled: true },
{ value: '4', label: 'The Riddler' },
{ value: '5', label: 'Lex Luthor' },
{ value: '6', label: 'Green Goblin' },
{ value: '7', label: 'Bain', disabled: true },
{ value: '8', label: 'The Penguin' },
{ value: '9', label: 'Doctor Octopus' },
{ value: '10', label: 'Poison Ivy' },
{ value: '11', label: 'Magneto' },
{ value: '12', label: 'Mr. Glass' },
{ value: '13', label: 'General Zod' },
{ value: '14', label: 'Red Skull', disabled: true },
{ value: '15', label: 'Baron Von Zemo' }
];
我将此数组复制到另一个处于 react 状态的名为 optionsState
的数组
const [optionsState, setOptionsState] = useState(superVillains);
并应用了以下操作:
const index = 0;
optionsState[index]['selected'] = true;
console.log(optionsState[index]['selected']);
console.log(optionsState[index]);
console.log(optionsState);
这是控制台中的结果:
在第一个控制台输出中,所选值似乎应该为 true,第二个控制台输出也是如此,但在不更改代码的情况下,第三个控制台输出显示所选值为 false。
问题是:为什么 selected
值在没有对其应用任何操作(除了控制台日志语句之外)的情况下明显发生变化?
如果一个地方是另一个地方
console.log(optionsState[index]);
在最后一个控制台日志之后,它将显示与之前相同的内容:
{value: "1", label: "Thanos", selected: true}
所以我不知道这是浏览器的问题还是 react 状态的问题还是我的问题。
对此有什么想法吗?
最佳答案
既然你编辑了你的问题,我明白了:)
你正在改变你的状态,而 React 是基于不变性(谷歌了解更多),一个快速修复是:
setOptionsState(prevState => {
const oldOptions = [...prevState.optionsState];
oldOptions[index] = { ...oldOptions[index] , selected: true };
return { oldOptions };
})
关于javascript - 为什么这个数组中的值(显然)立即改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59108368/