javascript - componentDidUpdate 警告:已安排级联更新
问题描述
我有一个 React 组件的问题,该组件呈现多部分表单并从 API 产生结果。
结果会实时更新,因为用户通过表单字段选择项目,并且表单字段本身也会更新以删除不适用的选项。
我的 API 调用是在componentDidUpdate
. 我首先检查是否更新了表单,而不是结果或其他任何内容。然后我执行 API 调用并更新结果的状态和新的字段值。(没有无限循环!我很确定这一点。)
这在 Firefox 和 Safari 中运行良好。问题似乎出在 Chrome 中,后 API 调用setState
大约需要 4 秒(使用 Chrome 的性能工具,这似乎很大程度上是由于"componentDidUpdate Warning: Scheduled a cascading update"
。)。
我不明白的是:
- 它确实从 componentDidUpdate 内部更新状态,但只更新一次(对选定值的第一次更改会触发一次状态更改;API 结果是第二次状态更改)。这确定不是问题?
- 如果是问题,为什么Firefox和Safari没有问题?
- 我有另一个表单,代码基本相同,只是字段和选项更少,没有同样的问题。
似乎在将大量数据写入组件的状态时会发生此错误——在这种情况下,它类似于 400k。而且,当然,仅在 Chrome 中。
我试过到处找,我看到的都是关于无限循环的东西……这不是问题所在。有什么建议或类似的经历吗?
更新:
- 在不同的机器/浏览器上做了更多的测试。似乎问题出现在 Windows 和 Mac 上的 Chrome 和 Opera 中;但不在Windows 或 Mac 上的 Firefox 或 Safari 中。
- 我尝试针对具有较少数据(因此 API 加载的数据较少)的测试数据库运行应用程序,并且即使在 Chrome中也不会出现问题。尝试在 Chrome 中执行大型 setState 似乎是一个非常具体的问题。
应该包含一些代码......这里显然缺少很多;这似乎是问题所在。
componentDidUpdate(prevProps, prevState) {
if (this.state.results === prevState.results) {
this.updateSearchParams();
fetch(`/api/stories-in-text/search/?`+this.getSearchParams())
.then(response => response.json())
.then(json => {
this.setState(
{
results: json.result,
theme_options: json.themes,
titles_options: json.titles,
textual_collections_options: json.textual_collections,
characters_in_story_body_options: json.characters_in_story_body,
characters_in_frame_options: json.characters_in_frame,
places_in_story_body_options: json.places_in_story_body,
places_in_frame_options: json.places_in_frame,
component_has_data: true,
}
);
});
}
}
解决方案
推荐阅读
- javascript - JS:删除星号之间的前导和尾随空格(有效降价)
- group-by - clickhouse 下采样到 OHLC 时间条间隔
- python - 代码未在输出 excel 文件中创建新的 excel 表
- python - python文件带参数时如何使用cProfile mod?
- sql - How do I display records in the same row although I am using group by on 2 columns that appear in different rows right now?
- aws-lambda - serverless: When 302 redirect the custom header or set-cookie header not getting passed
- servicestack - ServiceStack:当在服务之外抛出异常时,AppHost.OnRequestEndCallbacks 处理程序被调用两次
- swift - 视口?还是相机?视野?旋转 iOS 设备上的变化
- generics - 是否可以自动推断出一种传递的泛型?
- python - Seaborn (violinplot) y 轴值过多