首页 > 解决方案 > 为什么这个数组中的值(显然)会立即改变

问题描述

我找不到任何类似的问题,我不知道那里会发生什么,(也许可能是愚蠢的)但我没有找到任何关于可能发生的事情的线索。

我有这个数组:

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' }
];

我将此数组复制到另一个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);

这是控制台中的结果:

控制台红色

在第一个控制台输出中,选择的值似乎是正确的,第二个控制台输出也是如此,但是在代码中没有任何更改的情况下,第三个控制台输出显示选择的值是错误的。

问题是:为什么selected值明显改变而不对其应用任何操作(除了控制台日志语句)?

如果一个地方另一个

console.log(optionsState[index]);

在最后一个控制台日志之后,它将显示与以前相同:

{value: "1", label: "Thanos", selected: true}

所以我不知道这是浏览器的问题还是反应状态的问题或我的问题。

对此有什么想法吗?

标签: javascriptarraysreactjsreact-hooks

解决方案


现在你编辑了你的问题,我明白了:)

你正在改变你的状态,并且反应基于不变性(谷歌更多),一个快速修复将是:

setOptionsState(prevState => {
  const oldOptions = [...prevState.optionsState];
  oldOptions[index] = { ...oldOptions[index] , selected: true };
  return { oldOptions };
})

推荐阅读