使用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>