首页 > 解决方案 > componentDidUpdate 警告:已安排级联更新

问题描述

我有一个 React 组件的问题,该组件呈现多部分表单并从 API 产生结果。

结果会实时更新,因为用户通过表单字段选择项目,并且表单字段本身也会更新以删除不适用的选项。

我的 API 调用是在componentDidUpdate. 我首先检查是否更新了表单,而不是结果或其他任何内容。然后我执行 API 调用并更新结果的状态和新的字段值。(没有无限循环!我很确定这一点。)

这在 Firefox 和 Safari 中运行良好。问题似乎出在 Chrome 中,后 API 调用setState大约需要 4 秒(使用 Chrome 的性能工具,这似乎很大程度上是由于"componentDidUpdate Warning: Scheduled a cascading update"。)。

我不明白的是:

似乎在将大量数据写入组件的状态时会发生此错误——在这种情况下,它类似于 400k。而且,当然,仅在 Chrome 中。

我试过到处找,我看到的都是关于无限循环的东西……这不是问题所在。有什么建议或类似的经历吗?


更新:


应该包含一些代码......这里显然缺少很多;这似乎是问题所在。

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


            });
        }

    }

标签: javascriptreactjs

解决方案


根据链接- Gaearon,警告意味着它所说的:您安排了级联更新。“级联”是指更新中的更新。React 首先通过调用 render 来协调树,然后提交 DOM 更改,然后调用生命周期钩子。如果你在 componentDidMount 中调用 setState,你会导致 React 重复循环:协调树,提交 DOM 更改,然后调用钩子。这是浪费。

您还可以在此处获取更多信息


推荐阅读