简体   繁体   English

反应 | DataGrid 不更新 State

[英]React | DataGrid does not update with changed State

I am currently working on a linktree using the Datagrid Component from MaterialUI.我目前正在使用 MaterialUI 中的 Datagrid 组件处理链接树。 Data can be displayed, but when I try to add a new entry there occurs the problem that the content remains the same.可以显示数据,但是当我尝试添加新条目时,会出现内容保持不变的问题。 The state changes, but without rendering the new data. state 发生变化,但没有呈现新数据。

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>
    );
}}

Mutating State变异 State

The reason that you don't get proper updates is that you mutated your state right here when you called obj.push :您没有得到正确更新的原因是您在调用obj.push时在此处对 state 进行了变异:

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 is a "pass by reference" language ( mostly ), so obj is a new variable that stores the same reference to the same array object as this.state.linksData . Javascript 是一种“按引用传递”语言( 主要是),因此obj是一个新变量,它存储与 this.state.linkData 相同的array this.state.linksData的相同引用So you cannot call mutating methods on obj .所以你不能在obj上调用变异方法。

Solution解决方案

Set linksData to a new array by copying the contents of the old array.通过复制旧数组的内容将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]
    }));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM