【发布时间】:2020-06-01 09:36:48
【问题描述】:
我从根本上误解了 React 钩子,尤其是 useState 函数。为什么下面的代码不更新旧数组的索引,而是将trick的值设置为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