简体   繁体   中英

Unable to update state in ReactJS

I am building a data visualization where I need to pass the data from api to the chart component. The chart component loads fine for the first time but in the subsequent attempts the chart fails to load without any error. I am suspecting this to be an issue with the states being updated in the chart component. Upon debugging, I could find that the state is not updating intermittently due to which the chart does not load. Here is what the code looks like

HomePage.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}
 />

In the chart component, I receive the data from the props and set the state and my understanding is that whenever the state changes, the chart should be redrawn (this works but in some cases the state is never set or set to an empty object due to which the chart doesn't get created

Chart Component

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

Any suggestions on what I am doing wrong here? How can I ensure that the state is correctly set in the chart component?

Try Setting the State in the ChartComponent using componentWillReceiveProps lifecycle method .

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将触发重新渲染而不是在图表组件中再次设置状态

For anyone who might face the same issue, I fixed it by making following changes

  1. I was updating the state and calling the next function one after another. I changed it so that the next function is called in the callback of setState.
  2. In the child component, I added a componentShouldUpdate() function where I added return a false for unnecessary re-renders

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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