簡體   English   中英

反應 | DataGrid 不更新 State

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

我目前正在使用 MaterialUI 中的 Datagrid 組件處理鏈接樹。 可以顯示數據,但是當我嘗試添加新條目時,會出現內容保持不變的問題。 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>
    );
}}

變異 State

您沒有得到正確更新的原因是您在調用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 是一種“按引用傳遞”語言( 主要是),因此obj是一個新變量,它存儲與 this.state.linkData 相同的array this.state.linksData的相同引用所以你不能在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]
    }));
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM