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

8 篇文章 0 订阅

问题

这两天用create-react-app创建了一个新的React项目,在项目运行的时候,似乎有意想不到的事情发生,组件的componentDidMount方法被触发了两次。
在这里插入图片描述
而更早的项目,同样采用create-react-app创建的一个项目,却没有这个问题,当时真是一脸懵逼。。。

排查

首先想到的是前几天将本地的create-react-app升级过,问题是不是create-react-app升级导致的,转而一想应该没关系。后来去仔细比较了两个项目的package.json文件,发现之前的项目,React用的是17.x版本;而问题项目用的却是18.2.0版本的React

后来去React官方Github,果然找到关于18版本的一些Feature,链接:https://github.com/facebook/react/blob/main/CHANGELOG.md#breaking-changes

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.

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

解决方案

知道了原因之后,解决方案也很简单,将index.tsx或者index.js文件里的React.StrictMode高阶组件包围去掉即可。
修改前:

root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

修改后:

root.render(
  // 去除React.StrictMode
  // <React.StrictMode>
    <App />
  // </React.StrictMode>
);

至此,问题便完美的解决😄

  • 7
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值