Codesandbox的例子。https:/codesandbox.iosreact-table-state-not-updating-hmquq?file=srcApp.js。
我使用的是 反应表 包(7.1.0版本)。
我有一个显示一些发票的表格,如下所示。
用户应该能够选择其中的一些或全部项目,使用 selected
复选框。
该 selected
字段不是数据的一部分。然而,当用户点击 selected
复选框,该字段应该被切换,一个存储文档编号的数组应该被填充。
为了存储文档编号,我有一个有状态的getter和setter。
const [selectedInvoiceIds, setSelectedInvoiceIds] = useState([]);
为了填充字段,我试图简单地将文档编号添加到数组中,不可改变地,从... ... onChange
的复选框。
{
Header: "Selected",
accessor: "selected",
Cell: item => {
const { documentNumber } = item.row.values;
return (
<input
type="checkbox"
checked={selectedInvoiceIds.includes(documentNumber)}
onChange={() => {
setSelectedInvoiceIds([...selectedInvoiceIds, documentNumber]);
}}
/>
);
}
}
当第一次点击一个复选框时,该复选框就会被点击。selectedInvoiceIds
变得有人气。
selectedInvoiceIds: ["706942"]
问题是:
checked={selectedInvoiceIds.includes(documentNumber)}
selectedInvoiceIds
价值得到 覆写 当添加了另一个文档编号时,而不是被添加到,就像状态重新初始化为------。[]
介于两者之间。能否解释一下为什么会出现这些状态问题,如何规避?
我知道 useTableState
的值,但我不知道如何将它应用到这个用例中。
Codesandbox的例子。https:/codesandbox.iosreact-table-state-not-updating-hmquq?file=srcApp.js。
在这段代码中有多个问题。
// 1) updates to state should should use callback function if it uses prv state
return (
<input
type="checkbox"
checked={selectedInvoiceIds.includes(documentNumber)}
onChange={() => {
setSelectedInvoiceIds(prvSelectedInovicesId => [...prvSelectedInovicesId, documentNumber]);
}}
/>
);
// 2) also columns is using useMemo, however not providing dependencies, so columns are not being updated when the selectedInvociesIds state gets updated
// 3) you are not yet handling the toggle, this mean you are just always just adding to the array and not removing from it
这里是一个工作版本的代码沙盒https:/codesandbox.iosreact-table-state-not-updating-wkri3?file=srcApp.js。
因为使用了useMemo,所以在最后一个参数中加入数组。
const columns = React.useMemo(
// ....
,
[selectedInvoiceIds]
);
由于我们需要切换复选框,所以更合理的做法是将选中的id保存在对象中,而不是数组中,然后像这样进行更新。
setSelectedInvoices({
...selectedInovicesIds,
documentNumber: !selectedInovicesIds[documentNumber]}
)
所以它将切换标记