为什么componentDidUpdate会多次运行

问题描述 投票:0回答:2

我真的不明白反应生命周期。我在componentDidUpdate()中运行console.log,看到它运行了多次Console showed that componentDidUpdate ran 3 times

reactjs react-lifecycle
2个回答
1
投票

更新发生后立即调用componentDidUpdate()

您的问题可能会因为州已被更改,道具收到或父母重新获得。

如果您是React的新手,我建议您阅读以下文章:Post-Render with componentDidUpdate()


1
投票

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

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

当你改变你的状态或道具时,调用componentDidUpdate,apiCall函数通过fetchaxios发出http请求,并使用setState函数改变状态两次。

每当state改变时,新的render()被调用,componentDidUpdate跟随。

但条件

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

可能不再满足,只是在此时控制台记录而不是调用apiCall函数,这将触发无限循环。

希望能帮助到你。

© www.soinside.com 2019 - 2024. All rights reserved.