【发布时间】:2020-05-30 12:43:01
【问题描述】:
代码沙盒示例:https://codesandbox.io/s/react-table-state-not-updating-hmquq?file=/src/App.js
我正在使用react-table 包(版本 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值会在添加另一个文档编号时被覆盖,而不是被添加到其中,就好像状态正在重新初始化为介于两者之间的[]。
能否解释为什么会出现这些状态问题以及如何解决?
我知道 react-table 公开了 useTableState 值,但我不知道如何将其应用于此用例。
代码沙盒示例:https://codesandbox.io/s/react-table-state-not-updating-hmquq?file=/src/App.js
【问题讨论】:
标签: javascript reactjs state react-table