我正在单击复选框。当我选中复选框时,我正在尝试更新状态,但它不会立即更新。我创建了一个名为handleAllCheckbox
的onchange事件。
这是我的代码- const [hello,setHello] = useState(false);
const handleAllCheckbox = (e) => {
setHello(!hello);
if (!hello) {
contactList.map((item) => {
Ids.push(item._id)
});
setTheArray(...theArray, Ids);
}
else {
const newIds = []
setTheArray(...theArray, newIds);
}
}
我想如果hello
为true
,那么theArray
必须有ID;如果为false,则theArray
应该为空。
答案 0 :(得分:1)
如果要处理任何副作用,则应使用useEffect
,副作用意味着do something when a particular state change
。因此,根据您的情况,可以参考以下内容
import { useState, useEffect } from 'react';
const [hello, setHello] = useState(false);
useEffect(() => {
if (!hello) {
contactList.map((item) => {
Ids.push(item._id)
});
setTheArray(...theArray, Ids);
}
else {
const newIds = []
setTheArray(...theArray, newIds);
}
}, [hello]);
const handleAllCheckbox = () => setHello(!hello);
将[hello]
作为useEffect
的第二个参数,它表示do something whenever "hello" state is updated
。因此,现在您的代码也变得更加简洁,handleAllCheckbox
只关心处理状态hello
,并且每当hello
的值被更新时,useEffect
都会处理此问题>