前端 | 如何处理 React18 componentDidMount 重复执行两次的问题 | React

Appleex
Appleex
发布于 2023-05-01 / 290 阅读
0
0

前端 | 如何处理 React18 componentDidMount 重复执行两次的问题 | React

前端 | 如何处理 React18 componentDidMount重复执行两次的问题 | React

问题描述

按照 React 官网推荐方式创建项目,在运行项目的时,发现组件的 componentDidMount 方法被触发了两次。但是在旧项目中并没有这样的问题,于是觉得奇怪,以为是自己哪里使用错了,一直在排查。经过查阅官方文档以及网上资料,终于发现了问题所在。

内容分析

比较两个项目的 package.json 文件,发现旧项目 React 用的是 17.x 版本;而新项目用的是 18.x 版本。

后来在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>
    <App />
  // </React.StrictMode>
);

结尾

本期的内容就到这里,路过的小伙伴记得支持一下哦!


评论