我从根本上误解了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
}
您可以尝试这个。
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
}
尝试这个
const updatedTrick = () => {
modifyTrick(oldTrick => {
let newTrick = [...oldTrick];
newTrick[0] = 1;
return newTrick;
})
}