我真的不明白反应生命周期。我在componentDidUpdate()中运行console.log,看到它运行了多次Console showed that componentDidUpdate ran 3 times
更新发生后立即调用componentDidUpdate()
。
您的问题可能会因为州已被更改,道具收到或父母重新获得。
如果您是React的新手,我建议您阅读以下文章:Post-Render with componentDidUpdate()
当问题发生时,我可以给你一个额外的例子,因为我看不到你的代码。
componentDidUpdate(prevProps, prevState) {
const { something } = this.props;
if (prevProps.something !== something) this.apiCall();
console.log('something')
}
当你改变你的状态或道具时,调用componentDidUpdate
,apiCall函数通过fetch
或axios
发出http请求,并使用setState
函数改变状态两次。
每当state
改变时,新的render()
被调用,componentDidUpdate
跟随。
但条件
if (prevProps.something !== something) this.apiCall();
可能不再满足,只是在此时控制台记录而不是调用apiCall
函数,这将触发无限循环。
希望能帮助到你。