当我试图将对象添加到组件内的钩子时,它工作得很好-有点。似乎无论我做什么来获得钩子更新与选定项目的整个数组。它总是缺少最后选择的对象。
假设我选择项目1,2,5 -那么钩子就少了5假设我选择了1,2,4,5但是取消选择了2那么钩子就得到了所有选中的项目但没有取消选择项目2
这是我的代码。
const [selected, setSelected] = React.useState<string[]>()
React.useEffect(() => {
const getBrands = async () => {
const user = await getUser()
setSelected(user?.brands)
}
getBrands()
}
, [])
const toggleSelection = async(item: string) => {
console.log("clicked: ", item)
if (selected === undefined){
setSelected([item])
}
if (selected?.includes(item)) {
setSelected(selected.filter((i) => i !== item))
} else {
setSelected([...selected, item])
}
await updateUser({brands: selected})
}
控制台输出:
clicked: 2
Updating with Object {
"brands": Array [
"1",
"3",
"5",
],
}
clicked: 4
Updating with Object {
"brands": Array [
"1",
"3",
"5",
"2",
],
我相信这个问题是重复的,请查看这个链接
我希望这个工作对你有用:
...
const toggleSelection = (item: string) => {
console.log("clicked: ", item)
if (selected === undefined){
setSelected([item])
}
if (selected?.includes(item)) {
setSelected(selected.filter((i) => i !== item))
} else {
setSelected([...selected, item])
}
}
useEffect(() => {
// 'selected' will be updated here
async function asyncCall() {
if(selected.length>0)
await updateUser({brands: selected})
}
asyncCall();
}
, [selected])