reactjs - 为什么官方文档建议在 setState 中使用 componentDidMount 而不是回调?

标签 reactjs

https://facebook.github.io/react/docs/react-component.html#setstate

我似乎官方文档说:

The second parameter to setState() is an optional callback function that will be executed once setState is completed and the component is re-rendered. Generally we recommend using componentDidUpdate() for such logic instead.

当我们需要使用最新状态时,为什么他们建议使用 componentDidUpdate 而不是回调?

最佳答案

componentDidUpdate 也会在每次更新发生后立即调用。此时,最新状态已更新。

将所有检查状态逻辑放在 componentDidUpdate 中比每个 setState 的许多 callback 更容易管理。

顺便说一句,如果您使用 redux,我们不会在您的组件中执行 setState 操作。 More about redux

注意:初始渲染时不会调用componentDidUpdate

了解更多组件生命周期 https://facebook.github.io/react/docs/react-component.html#componentdidupdate

关于reactjs - 为什么官方文档建议在 setState 中使用 componentDidMount 而不是回调?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45587645/

相关文章:

javascript - React 如何使用 setState 和 Map 值

javascript - 顺序异步函数

mysql - 在 React 上尝试 .map 内的“收藏夹”选项卡。我无法更改 mysql 表上的 bool 类型

reactjs - HOC react redux firebase。 (错误 : Firebase storage is required to upload files)

reactjs - 如何从 create-react-app 获取类声明?

javascript - 通过 WebPack 将 Bootstrap 加载到 Wordpress 时,ReactJS 代码拆分会导致错误

javascript - 如何构建 React 应用程序的 docker 镜像?

javascript - 在 Promise 完成后让 React 重新渲染

reactjs - 创建 react "development"构建

javascript - 如何修复 reactjs 中的 "Expected an assignment or function call and instead saw an expression"?