我有一个简单的 hello-world 示例可以试用 useState
钩;但是当我在控制台输出测试信息时,我发现每当我启用 useState
控制台记录两倍的信息。
见 example在 CodeSandbox 中(调试信息显示在控制台中)。
最佳答案
控制台语句在函数体中,React
将在每次渲染时执行函数体。
React
将再次执行函数体,然后使用更新的值记录状态。 As you are using the
React.StrictMode
it can render the component more than once. That is the reason you see the console logs multiple times.The commit phase is usually very fast, but rendering can be slow. For this reason, the upcoming concurrent mode (which is not enabled by default yet) breaks the rendering work into pieces, pausing and resuming the work to avoid blocking the browser. This means that React may invoke render phase lifecycles more than once before committing, or it may invoke them without committing at all (because of an error or a higher priority interruption). Render phase lifecycles include the following class component methods:
- constructor
- componentWillMount (or UNSAFE_componentWillMount)
- componentWillReceiveProps (or UNSAFE_componentWillReceiveProps)
- componentWillUpdate (or UNSAFE_componentWillUpdate)
- getDerivedStateFromProps
- shouldComponentUpdate render
- setState updater functions (the first argument)
Because the above methods might be called more than once, it’s important that they do not contain side-effects. Ignoring this rule can lead to a variety of problems, including memory leaks and invalid application state. Unfortunately, it can be difficult to detect these problems as they can often be non-deterministic.
您可以阅读更多关于
React.StrictMode
的信息here
关于reactjs - 为什么 useState 导致 dom 渲染两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61112615/