繁体   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