javascript - 无法在 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>
);
}
关于我在这里做错了什么有什么建议吗?如何确保在图表组件中正确设置状态?
解决方案
对于可能面临相同问题的任何人,我通过进行以下更改来修复它
- 我正在更新状态并一个接一个地调用下一个函数。我改变了它,以便在 setState 的回调中调用下一个函数。
- 在子组件中,我添加了一个 componentShouldUpdate() 函数,我在其中添加了 return a false 用于不必要的重新渲染
推荐阅读
- facebook - 是否可以使用图形 api 从 facebook 组获取销售帖子
- node.js - 如何修复 XMLHttpRequest 已被 CORS 策略阻止
- c# - 如果 ClassInitialize 或 TestInitalize 失败,您如何中止运行测试用例?
- c# - 如果过滤器值为空,Entity Framework Core 返回所有数据
- python - 当我尝试对简单的化学反应进行敏感性分析时,SALib 返回错误
- c# - 如何从目录符号链接中获取文件
- python - PyInstaller 无法使用 geopandas 和 fiona 创建 exe。即使我在 .spec 文件中进行了一些更改,exe 也无法正常工作
- vue.js - Bootstrap 4 Dropdown(使用 vue.js 打开)中的复选框不可选中
- scala - 我应该添加哪个依赖项以使用 intelliJ 使用 scala-spark 在 s3 中获取 txt 文件?
- python - 无法使用python2对汉字进行unicode