reactjs - 为什么 componentDidUpdate 运行多次
问题描述
我真的不明白反应生命周期。我在 componentDidUpdate() 中运行 console.log 并看到它运行了多次 控制台显示 componentDidUpdate 运行了 3 次
解决方案
当你的问题发生时,也许我可以给你一个额外的例子,因为我看不到你的代码。
componentDidUpdate(prevProps, prevState) {
const { something } = this.props;
if (prevProps.something !== something) this.apiCall();
console.log('something')
}
当您更改状态或道具时,componentDidUpdate
正在调用,并且 apiCall 函数通过fetch
or发出 http 请求axios
,并使用函数更改状态两次setState
。
每当state
发生更改时,都会render()
调用并componentDidUpdate
遵循新的。
但条件
if (prevProps.something !== something) this.apiCall();
可能不再满足,此时只需控制台日志记录,而不是调用apiCall
会触发无限循环的函数。
希望能帮助到你。
推荐阅读
- postgresql - 使用 pgx 从 Postgres 扫描 PostGIS 点时,接口 {} 是字符串,而不是 []uint8
- javascript - Set-Cookie 在 Chrome 和 Dolphin 中不起作用 - 有两个网站
- java - 我可以使用 Autowired 构造函数将模拟注入原型 bean 吗?
- java - 通过java代码在git bash中输入一系列命令
- angular - 延迟加载模块中的路由总是重新加载根组件
- php - PHP月份数组原始值
- java - 何时在 Jython 中使用 cleanup()
- aspnetboilerplate - 在 Asp.net 样板项目中使用剑道 ui
- python - 无法使用 SMTPLIB 打开附件
- vue.js - Vue.js - 从 Vuex Store 的突变内部控制路由器