gpt4 book ai didi

javascript - 如何使用状态 Hook 更新数组的单个元素?

转载 作者:行者123 更新时间:2023-12-05 04:21:21 26 4
gpt4 key购买 nike

这是我正在处理的代码部分,

这是我的钩子(Hook)

const [array, setArray] = useState(
JSON.parse(localStorage.getItem("notes")) ?? []
);

这是函数,

  const save = () => {
let info = one.current.value;
console.log(newIndex, " and ", info);
console.log("this si array element -> ", array[newIndex - 1]);
array[newIndex - 1] = info;
if (newIndex !== undefined) {
setArray((e) => {
return e.map((e1, i) => {
if (i + 1 === newIndex) {
return [...e ];
}
});
});
}
};

info 有我想更新的正确输入,newIndex 有我想更新的元素的索引。

你能建议我在这部分需要改变什么吗,这是上面功能的一部分,

setArray((e) => {
return e.map((e1, i) => {
if (i + 1 === newIndex) {
return [...e ];
}
});

最佳答案

要更新您的阵列,您不需要映射任何东西。你只需要复制数组,在右边的索引处修改复制的数组并返回复制的数组。 React 会处理剩下的事情。

复制数组很重要,否则 React 不会注意到更改。 useState 只记住数组在内存中的地址。只有通过具有新地址的新数组,useState 才会真正触发。

以下是我对您的 save() 函数的看法:

const save = () => {
let info = one.current.value;
if (newIndex !== undefined) {
console.log(newIndex, " and ", info);
console.log("this is array element -> ", array[newIndex - 1]);
setArray((e) => {
let temp = [...e];
temp[newIndex - 1] = info;
return temp;
});
}
};

试过codesandbox中的代码,我想这就是你想要的。

关于javascript - 如何使用状态 Hook 更新数组的单个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74234468/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com