首页 > 解决方案 > 更改状态值在 react-table 上无法正常工作

问题描述

我正在尝试使用 react-table 为每一行数据添加一个“删除”按钮。按钮拼接数据并在按下时从数据中删除该行。第一次单击“删除”按钮时,它可以正常工作。然而,在第二次按下时没有任何反应。出于某种原因changeData,不会更改第二次运行的数据。为什么会发生这种情况?

function DataTable({columns, data_rows}) {
    const [data, changeData] = useState(data_rows);

    if (columns[0].Header !== "Action") {
        columns.unshift({
            Header: 'Action'
        });
    }
    columns[0]['columns'] = [{
        Header: ' ', Cell: ({row}) => (
            <ButtonGroup>
                <Button className="button-dark button-sm" onClick={() => {
                    const dataCopy = [...data];
                    dataCopy.splice(row.index, 1);
                    changeData(dataCopy);}}>
                    Remove
                </Button>
            </ButtonGroup>
        )
    }]
    const {
        getTableProps,
        getTableBodyProps,
        headerGroups,
        rows,
        prepareRow
    } = useTable({
        columns,
        data
    });


    return (
        <table {...getTableProps()}>
            <thead>
            {headerGroups.map(headerGroup => (
                <tr {...headerGroup.getHeaderGroupProps()}>
                    {headerGroup.headers.map(column => (
                        <th {...column.getHeaderProps()}>{column.render("Header")}</th>
                    ))}
                </tr>
            ))}
            </thead>
            <tbody {...getTableBodyProps()}>
            {rows.map((row, i) => {
                prepareRow(row);
                return (
                    <tr {...row.getRowProps()}>
                        {row.cells.map(cell => {
                            return <td {...cell.getCellProps()}>{cell.render("Cell")}</td>;
                        })}
                    </tr>
                );
            })}
            </tbody>
        </table>
    );
}

标签: reactjsreact-table

解决方案


推荐阅读