Next.js & React component render twice bug All In One
error ❌
React.StrictMode
https://github.com/facebook/react/issues/15074
https://reactjs.org/docs/strict-mode.html
New
Strict Mode
Behaviors
https://reactjs.org/blog/2022/03/29/react-v18.html#new-strict-mode-behaviors
solution ✅
// next.config.js
module.exports = {
- reactStrictMode: true,
+ reactStrictMode: false,
}
https://nextjs.org/docs/api-reference/next.config.js/react-strict-mode
demos
React 问题复现条件:
- state function component
有状态
函数组件 - state class component
有状态
函数组件 - hooks component
钩子
组件
??? pure react app testing ???
Next.js 问题复现条件:
-
state function component
有状态
函数组件 -
state class component
有状态
函数组件 -
hooks component
钩子
组件 -
stateless function component
无状态
函数组件 -
stateless class component
无状态
函数组件
import React, {
useEffect,
useRef,
} from "react";
import { createRoot } from 'react-dom/client';
// export default function Home() {
function Home() {
const log = console.log;
log(`v18 createRoot =\n`, createRoot);
let root = useRef(null);
useEffect(() => {
// v18
console.log(`root =`, root)
console.log(`root.current =`, root.current)
if(!root.current) {
const App = document.getElementById('v18-app');
root.current = createRoot(App);
// JSX
root.current.render(<h1>Develop. Preview. Ship. 🚀 React v18 🆕</h1>);
}
}, []);
return (
<div id="v18-app">...loading</div>
)
};
export default React.memo(Home);
/*
Warning: You are calling ReactDOMClient.createRoot() on a container that has already been passed to createRoot() before.
Instead, call root.render() on the existing root instead if you want to update it.
// Assignments to the 'root' variable from inside React Hook useEffect will be lost after each render.
// To preserve the value over time, store it in a useRef Hook and keep the mutable value in the '.current' property.
// Otherwise, you can move this variable directly inside useEffect.eslintreact-hooks/exhaustive-deps
// https://github.com/facebook/react/issues/14920
*/
refs
https://github.com/web-full-stack/nextjs-ssr/issues/6#issuecomment-1315425580
next.js react components render twice bug ❌
https://deniapps.com/blog/why-the-react-component-renders-twice
https://www.heissenberger.at/en/blog/react-components-reder-twice/
https://mariosfakiolas.com/blog/my-react-components-render-twice-and-drive-me-crazy/
©xgqfrms 2012-2021
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
原文地址:http://www.cnblogs.com/xgqfrms/p/16894519.html