doubleyong
管理员
管理员
  • 最后登录2024-05-08
  • 发帖数1168
  • 最爱沙发
  • 喜欢达人
  • 原创写手
  • 社区居民
  • 忠实会员
阅读:1621回复:0

[react]React 18 componentDidMount重复执行两次的解决方案

楼主#
更多 发布于:2022-09-23 11:24
问题:


最近使用create-react-app创建了React项目,在项目运行时,发现组件的componentDidMount方法被触发了两次.




原因:


Stricter Strict Mode: In the future, React will provide a feature that lets components preserve state between unmounts. To prepare for it, React 18 introduces a new development-only check to Strict Mode. React will automatically unmount and remount every component, whenever a component mounts for the first time, restoring the previous state on the second mount. If this breaks your app, consider removing Strict Mode until you can fix the components to be resilient to remounting with existing state.
来自:https://github.com/facebook/react/blob/main/CHANGELOG.md#breaking-changes






大意如下:


在未来,React会提供一个新特性,该特性会使得组件取消加载后能维持状态。React 18会在Strict Mode中引入一个新的开发模式。React将会对每一个组件自动取消加载并重新加载。如果其干扰了你的应用,移除Strict Mode就能够修复组件重新加载的问题。(本人蹩脚的英语翻译的,将就这看。。。)




解决方案:


将 index.js文件里的React.StrictMode高阶组件包围去掉即可。
root.render(
  // 去除React.StrictMode
  // <React.StrictMode>
    <App />
  // </React.StrictMode>
);
知识需要管理,知识需要分享
游客


返回顶部

公众号

公众号