首页 > 解决方案 > 为什么 componentDidUpdate 运行多次

问题描述

我真的不明白反应生命周期。我在 componentDidUpdate() 中运行 console.log 并看到它运行了多次 控制台显示 componentDidUpdate 运行了 3 次

标签: reactjsreact-lifecycle

解决方案


当你的问题发生时,也许我可以给你一个额外的例子,因为我看不到你的代码。

componentDidUpdate(prevProps, prevState) {
        const { something } = this.props;
        if (prevProps.something !== something) this.apiCall();
        console.log('something')
}

当您更改状态或道具时,componentDidUpdate正在调用,并且 apiCall 函数通过fetchor发出 http 请求axios,并使用函数更改状态两次setState

每当state发生更改时,都会render()调用并componentDidUpdate遵循新的。

但条件

if (prevProps.something !== something) this.apiCall();

可能不再满足,此时只需控制台日志记录,而不是调用apiCall会触发无限循环的函数。

希望能帮助到你。


推荐阅读