簡體   English   中英

無法在 ReactJS 中更新狀態

[英]Unable to update state in ReactJS

我正在構建一個數據可視化,我需要將數據從 api 傳遞到圖表組件。 圖表組件第一次加載正常,但在隨后的嘗試中,圖表無法加載且沒有任何錯誤。 我懷疑這是圖表組件中更新狀態的問題。 在調試時,我可以發現由於圖表未加載,狀態不會間歇性更新。 這是代碼的樣子

主頁.js

async componentDidMount() {
    await this.getDataFromApi(); //Gets data for the charts
    await this.prepareDataForChart(); //Prepares the data for the charts
}

/*When the new date range is selected and the submit button is clicked, 
  this method handles the click and gets the new data and prepares it for the chart*/

async handleButtonClick() {
    await this.getDataFromApi();
    await this.prepareDataForChart();
    this.setState({ shouldRefresh: true });
}
/*This is where I pass the data to the chart component*/
 <LineChart
     chartData={this.state.chartTotalPopulation}
 />

在圖表組件中,我從道具接收數據並設置狀態,我的理解是,每當狀態發生變化時,都應該重新繪制圖表(這可行,但在某些情況下,狀態永遠不會設置或設置為空對象圖表不會被創建

圖表組件

this.state = {
        chartData: {}
    };
}

componentDidUpdate() {
    let chartData = this.props.chartData;
    //Check before updating the state to avoid infinite dom updates
    if (chartData.labels.length > 0 && this.state.chartData.labels.length ===0) { 
      this.setState({ chartData: chartData });
    }
}

render() {
    return (
        <div className="chartContianer">
            <Line data={this.state.chartData}/>
        </div>
    );
  }

關於我在這里做錯了什么的任何建議? 如何確保在圖表組件中正確設置狀態?

嘗試使用componentWillReceiveProps生命周期方法在 ChartComponent 中設置狀態。

componentWillReceiveProps (){
 let chartData = this.props.chartData;
    //Check before updating the state to avoid infinite dom updates
    if (chartData.labels.length > 0 && this.state.chartData.labels.length ===0) { 
      this.setState({ chartData: chartData });
    }
}

在圖表組件中直接傳遞this.props.chartData將觸發重新渲染而不是在圖表組件中再次設置狀態

對於可能面臨同樣問題的任何人,我通過進行以下更改來修復它

  1. 我正在更新狀態並一個接一個地調用下一個函數。 我改變了它,以便在 setState 的回調中調用下一個函數。
  2. 在子組件中,我添加了一個 componentShouldUpdate() 函數,我添加了 return false 以進行不必要的重新渲染

暫無
暫無

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

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