使用useState hook实现持久值在多个函数调用之间的保持
<p>我在一个按钮上调用“deleteDepartment”函数来删除表格中的部门行。从表格中(我正在使用使用tanstack表的shancn表)获取“selectedRows”钩子中的选定行索引(将setSelectedRows作为prop传递给表格组件,该组件从表格中的rowSelection钩子中获取值)。</p>
<p><strong>问题是</strong>:我能够删除前两三行没有任何问题,但是当我继续删除时,“rowSelection”状态会保存来自上一个函数调用的值,并将其添加到当前选定的行数组中。</p>
<p><em><strong>示例</strong></em>:如果我删除行['1'],下一次我点击按钮删除行2,那么“rowSelection”的值应该只是['2'],但它会添加到先前的值中,如['1','2']。</p>
<p>我迷失在为什么会发生这种行为。我认为这可能是由于闭包和异步性质导致的,因此我使用了useCallback钩子,但是没有用。请有更好知识的人帮帮忙</p>
<pre class="brush:php;toolbar:false;">const DepartmentsAndRolesPage = () => {
const [departments, setDepartments] = useState<departmentTypes[]>([]);
const [selectedRows, setSelectedRows] = useState({});
const [rowIndexes, setRowIndexes] = useState<string[]>([]);
useEffect(() => {
getDepartment();
}, []);
useEffect(() => {
const indexesToAdd = Object.keys(selectedRows);
setRowIndexes(indexesToAdd);
}, [selectedRows]);
const deleteDepartment = useCallback(async () => {
if (rowIndexes.length === 0) {
return;
}
if (rowIndexes.length === 1) {
const filteredDepartment = departments[parseInt(rowIndexes[0])];
const id = filteredDepartment._id;
const response = await axios.delete(`/api/department/delete/${id}`);
if (response.statusText === "OK") {
getDepartment();
setSelectedRows({});
}
return;
}
if (rowIndexes.length > 1) {
const departmentsToDelete = rowIndexes.map(
(rowIndex) => departments[parseInt(rowIndex)]._id
);
const response = await axios.post("/api/department/delete", {
_id: departmentsToDelete,
});
if (response.statusText === "OK") {
getDepartment();
setSelectedRows({});
}
return;
}
}, [departments, rowIndexes, toast]);
Return (rest of the UI code here.... )</pre>
<p><br /></p>