前天在写 React 某个 Demo 代码时发现 React 组件渲染了两次,开始以为是 state 原因,因为函数式组件不使用useState钩子只渲染了一次,但是我思考不明白为什么 React 类组件和使用了useState钩子,开始猜测为因为state原因,
而后在 StackOverflow 上面提问后经热心网友的告知才知道答案,是因为我使用了 React 严格模式,即使用React.StrictMode组件
React StrictMode 文档https://reactjs.org/docs/strict-mode.html
文档上面给出了使用React.StrictMode的副作用
Strict mode can’t automatically detect side effects for you, but it can help you spot them by making them a little more deterministic. This is done by intentionally double-invoking the following methods:
- Class component
constructormethod- The
rendermethodsetStateupdater functions (the first argument)- The static
getDerivedStateFromPropslifecycle- The
shouldComponentUpdatemethod
这次最大的问题还是出在大意上,在找问题时忽略了index.js,因为是使用create-react-app创建了,App.js和index.js都包含了StrictMode
#React 函数组件在定时器获取 State 问题
在上面点开控制台后连续点击三次Click me可以看到输出了
0
0
1 这是因为变量引用和异步的问题,在函数式很容易遇到因为变量引用而导致的不刷新,最常见的就是当使用useEffect这些需要填写依赖的需要将依赖正确的填写,否者就会出现因为变量引用导致值无变化进而出现问题