【问题标题】:React | DataGrid does not update with changed State反应 | DataGrid 不会随着更改的状态而更新
【发布时间】:2021-02-10 03:05:05
【问题描述】:

我目前正在使用 MaterialUI 中的 Datagrid 组件处理链接树。 可以显示数据,但是当我尝试添加新条目时,会出现内容保持不变的问题。状态发生变化,但没有渲染新数据。

const columns = [
{field: 'date', headerName: 'Date', width: 120},
{
    field: 'videoUrl',
    headerName: 'Video URL',
    width: 430,
    renderCell: (params) =>
            <a href={(params.value)}>{params.value}</a>
},
{field: 'description', headerName: 'Description', width: 130},
];


class Linktree extends React.Component {
    this.state = {
        newLink: "",
        newDescription: "",
    }
}

handleAddNewLink(newLink, description) {
    let obj = this.state.linksData
    let newEntry = {id: this.state.linksData.length+1, postDate: today, videoUrl: newLink, description: description}
    obj.push(newEntry)

    this.setState({linksData: obj})
}

render (){
    return (
        <div>
            <div style={{height: 400, width: '100%', backgroundColor: "white"}}>
                <DataGrid rows={!this.state.loading ? this.state.linksData : []} columns={columns} pageSize={5} hideFooterSelectedRowCount/>
            </div>
        </div>
    );
}}

【问题讨论】:

    标签: javascript reactjs material-ui state rendering


    【解决方案1】:

    变异状态

    你没有得到正确更新的原因是你在调用obj.push时改变了你的状态:

    handleAddNewLink(newLink, description) {
        let obj = this.state.linksData
        let newEntry = {id: this.state.linksData.length+1, postDate: today, videoUrl: newLink, description: description}
        obj.push(newEntry)
        this.setState({linksData: obj})
    }
    

    Javascript 是一种“通过引用传递”的语言 (mostly),因此 obj 是一个新变量,它存储与 this.state.linksData 相同的对同一 array 对象的引用。所以你不能在obj 上调用变异方法。

    解决方案

    通过复制旧数组的内容将linksData 设置为新数组。

    handleAddNewLink(newLink, description) {
        let newEntry = {id: this.state.linksData.length+1, postDate: today, videoUrl: newLink, description: description}
        this.setState(prevState => ({
          linksData: [...prevState.linksData, newEntry]
        }));
    }
    

    【讨论】:

      猜你喜欢
      • 2020-09-10
      • 2020-06-07
      • 2017-05-19
      • 1970-01-01
      • 1970-01-01
      • 2017-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多