问题:
最近使用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> ); |
|
|