使用反应表访问组件状态

时间:2020-08-17 17:52:06

标签: javascript reactjs react-hooks react-table react-table-v7

这是我的第一个问题,我只需要了解为什么在处理传递给react-table useTable钩子的Checkbox中的更改时为什么无法访问组件的实际状态。

const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    rows,
    prepareRow,
}: ITableInstance = useTable(
    {
        columns: tableColumns,
        data,
    },
    useRowSelect,
    (hooks: Hooks<any>) => {
            hooks.visibleColumns.push((tableColumns) => [
                {
                    id: 'selection',
                    Header: (headerCell: THeaderProps) => (
                        <Checkbox
                            {...headerCell.getToggleAllRowsSelectedProps()}
                            onChange={handleSelectAllRows(headerCell)}
                        />
                    ),
                    Cell: ({row}: TCellProps) => (
                        <Checkbox
                            {...row.getToggleRowSelectedProps()}
                            onChange={() => handleSelect((row.original as TSelectableTableRowData).selectionValue)}
                        />
                    ),
                },
                ...tableColumns,
            ]);
    }
);

这是我的Table组件状态和更改时的回调:

const [selected, setSelected] = React.useState<string[]>([]);

const handleSelect = (selectedValue: string) => {
    setSelected(selected.concat([selectedValue])); // When I reach here, state is always = [], but it must have one item, when I check second checkbox.
};

似乎每个复选框事件处理程序都使用其自己的反应状态。有什么想法为什么会那样吗?谢谢!

0 个答案:

没有答案