react组件mount好几次如何解决(mount,react,web开发)

时间:2024-04-28 04:33:14 作者 : 石家庄SEO 分类 : web开发
  • TAG :

react组件mount好几次的解决办法:1、找到并打开“index.tsx”或者“index.js”文件;2、找到“root.render(<React.StrictMode><App /></React.StrictMode>);”代码;3、将“React.StrictMode”高阶组件包围去掉即可。

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

问题

这两天用create-react-app创建了一个新的React项目,在项目运行的时候,似乎有意想不到的事情发生,组件的componentDidMount方法被触发了两次。

react组件mount好几次如何解决

而更早的项目,同样采用create-react-app创建的一个项目,却没有这个问题,当时真是一脸懵逼。。。

排查

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

后来去React官方Github,果然找到关于18版本的一些Featur

StricterStrictMode:Inthefuture,Reactwillprovideafeaturethatletscomponentspreservestatebetweenunmounts.Toprepareforit,React18introducesanewdevelopment-onlychecktoStrictMode.Reactwillautomaticallyunmountandremounteverycomponent,wheneveracomponentmountsforthefirsttime,restoringthepreviousstateonthesecondmount.Ifthisbreaksyourapp,considerremovingStrictModeuntilyoucanfixthecomponentstoberesilienttoremountingwithexistingstate.

大意如下:

在未来,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>);

 </div> <div class="zixun-tj-product adv-bottom"></div> </div> </div> <div class="prve-next-news">
本文:react组件mount好几次如何解决的详细内容,希望对您有所帮助,信息来源于网络。
上一篇:react中如何禁止button渲染下一篇:

4 人围观 / 0 条评论 ↓快速评论↓

(必须)

(必须,保密)

阿狸1 阿狸2 阿狸3 阿狸4 阿狸5 阿狸6 阿狸7 阿狸8 阿狸9 阿狸10 阿狸11 阿狸12 阿狸13 阿狸14 阿狸15 阿狸16 阿狸17 阿狸18