首页 > 解决方案 > 使用新状态数据刷新 Material-UI DataGrid 组件

问题描述

早上好,

我们正在使用 Material-UI 创建一个填充用户的 DataGrid 表,并希望能够使用按钮删除选定的条目(复选框)。

单击按钮会更新我们对象的状态(删除预期的行),Material-UI 的 DataGrid 元素将作为参数this.state.rows(如Stack Overflow 中所述)

下面显示的日志证明,在setState()重新渲染 DataGrid 组件(红色矩形)的调用(蓝色矩形)之后,确实更新了 state 元素。然而,视觉上没有任何变化:(

控制台日志

代码如下所示:

import { DataGrid } from '@material-ui/data-grid';
import * as React from 'react';

import Button from '@material-ui/core/Button';
import { makeStyles } from '@material-ui/core/styles';
import DeleteIcon from '@material-ui/icons/Delete';

class EmployeeGrid extends React.Component {

    constructor(props) {
        super(props);
        this.handleDelete = this.handleDelete.bind(this);
        this.hrefs = {}
        this.columns = [
            { field: 'id', headerName: 'ID', width: 70 },
            { field: 'firstName', headerName: 'First name', width: 130 },
            { field: 'lastName', headerName: 'Last name', width: 130 },
            { field: 'description', headerName: 'Description', width: 200 }
        ];
        
        let employeeList = [];
        let id = 1;
        for (const employee of this.props.employees) {
            this.hrefs[id] = employee.url;
            employeeList.push({
                id: id,
                firstName: employee.entity.firstName,
                lastName: employee.entity.lastName,
                description: employee.entity.description
            });
            id++;
        }
        console.log(this.hrefs)
        console.log(employeeList)
        this.state={rows: employeeList, //populate initial state with all employees from database
                    selected: [],
                    nbRender: 1}
        console.log(this.state.rows);
    }

    handleDelete() {
        for (let id of this.state.selected) {
            this.state.rows.splice(id - 1, 1); //delete rows that were selected
            this.props.onDelete(this.hrefs[id]); //delete from database
        }
        this.setState({rows: this.state.rows, selected: [], nbRender: 2}, () => {
            console.log(this.state.rows) //checks state is indeed updated
        });
        console.log(this.state.rows);
    }

    render() {
        console.log("In render of EmployeeGrid");
        console.log(this.state.rows)
        return (
            <div>
                <div style={{ height: 400, width: '100%' }}>
                    <DataGrid rows={this.state.rows} //populate grid with state.rows
                                columns={this.columns}
                                pageSize={this.props.pageSize}
                                checkboxSelection 
                                onSelectionChange={(newSelection) => {
                                    this.setState({selected: newSelection.rowIds})
                                }}/>
                </div>
                <div>
                    <Button variant="contained"
                            color="secondary"
                            startIcon={<DeleteIcon />}
                            onClick={this.handleDelete}>
                                Delete
                    </Button>
                </div>
            </div>   
        )
    }
}

export default EmployeeGrid;

编辑 1

经过更多分析,我们发现日志之所以在控制台日志中显示 4 行,是因为我们在 line 处就地更新了 state:

this.state.rows.splice(id - 1, 1); //delete rows that were selected

我们现在注意到以下行从未被调用,这反过来不会重新渲染页面更新。

 this.setState({rows: this.state.rows, selected: [], nbRender: 2}, () => {
            console.log(this.state.rows) //checks state is indeed updated
        });

再次感谢任何关于为什么会出现这种情况的想法!

干杯并保持安全

标签: javascriptreactjsdatagridmaterial-ui

解决方案


好像你在这里改变状态

this.state.rows.splice(id - 1, 1)

试试这个

handleDelete() {
    for (let id of this.state.selected) {
        this.props.onDelete(this.hrefs[id]); //delete from database
    }
    this.setState((prevState) => ({
      ...prevState,
      rows: prevState.rows.filter((row) => !prevState.selected.includes(row.id)),
      selected: [], 
      nbRender: 2
    }));
}

推荐阅读