使用React钩子更新数组

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

我从根本上误解了React挂钩,尤其是useState函数。为什么下面的代码不更新旧数组的索引,而是将把值设置为1?我了解如何使用React钩子将新项目推送到数组上,但是如何更新现有值?

const [trick, modifyTrick] = useState([null, null, null, null]);

const identityTrick = () => {
    modifyTrick(oldTrick => oldTrick) //works
}

const updatedTrick = () => {
    modifyTrick(oldTrick => oldTrick[0] = 1) //sets the entire value of trick to 1
}
reactjs react-hooks
2个回答
0
投票

您可以尝试这个。

const [trick, modifyTrick] = useState([null, null, null, null]);

const identityTrick = () => {
    modifyTrick(oldTrick => oldTrick) //works
}

const updatedTrick = () => {
    let newTrick = oldTrick;
    newTrick[0] = 1; 
    modifyTrick(newTrick) //Try this one
}

0
投票

尝试这个

  const updatedTrick = () => {
    modifyTrick(oldTrick => {
      let newTrick = [...oldTrick];
      newTrick[0] = 1;
      return newTrick;
    })
  }
© www.soinside.com 2019 - 2024. All rights reserved.