reactjs - 为什么 useState 导致 dom 渲染两次

标签 reactjs

我有一个简单的 hello-world 示例可以试用 useState钩;但是当我在控制台输出测试信息时,我发现每当我启用 useState控制台记录两倍的信息。

example在 CodeSandbox 中(调试信息显示在控制台中)。

最佳答案

控制台语句在函数体中,React将在每次渲染时执行函数体。

  • 在组件挂载时,由于 init 状态为空,控制台将打印一个空字符串。
  • 当您更新组件挂载状态时,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:

    1. constructor
      1. componentWillMount (or UNSAFE_componentWillMount)
      2. componentWillReceiveProps (or UNSAFE_componentWillReceiveProps)
      3. componentWillUpdate (or UNSAFE_componentWillUpdate)
      4. getDerivedStateFromProps
      5. shouldComponentUpdate render
      6. 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/

    相关文章:

    javascript - 使用 create-react-app 时如何获取 electro.js 文件的 typescript

    javascript - 需要有关在 React 应用程序中解析来自此 API 的 JSON 数据的帮助

    javascript - 正在编辑 Redux 状态而不派发任何操作

    javascript - 如何从api获取reactjs中的图像?

    html - 如何将远程 CSS 链接到 React 组件

    javascript - 如何使用 TypeScript 获取 React Child 的 offsetTop

    reactjs - 如何使用 Material UI 在选项卡上放置关闭按钮

    javascript - 将新数组而不是数组文字传递给 useState 显示空数组

    javascript - react native 和 MobX : How to create a global store?

    javascript - 在 React 中卸载组件到底意味着什么?卸载后会消失吗?