为什么我的反应组件在初始加载时渲染两次?

Why is my react component rendering twice on initial load?

我有一个名为 (First) 的功能组件

function First() {
    const [count,setCount]=useState(0)

    console.log("component first rendering") // this logging is happening twice


    return (
        <div>
            first component
        </div>
    )
}

当我最初 运行 应用程序 console 语句记录两次为什么会这样,它应该只记录一次,因为我没有明确更新状态。

我已经在代码沙箱中试过了 here 果然,它确实渲染了两次。这是因为,在 index.js 文件中,它使用 React.StrictMode.

According to this documentation:

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 functions:

  • Class component constructor, render, and shouldComponentUpdate methods

  • Functions passed to useState, useMemo, or useReducer

这通常是为了帮助仅在开发环境中发现副作用。它不适用于生产环境。

因此,如果您不希望它渲染两次,只需删除 index.js 文件中的 <React.StrictMode> </ React.StrictMode> 即可正常工作。

希望对您有所帮助:)

发生这种情况是因为您的应用程序包含在 React.StrictMode.

<React.StrictMode>
<First />
</React.StrictMode>

在 React 16.* 中为功能组件引入了严格模式。我们将我们的组件包装在 React.StrictMode 下以识别我们应用程序中的潜在错误。

StrictMode 有助于保持大型代码库的稳定性,并有助于升级到更新版本的 React。 StrictMode 在控制台中记录我们的应用程序可能存在的问题的错误:

React.StrictMode需要触发一些方法和生命周期钩子两次来解决这些问题:

  1. 这些方法可能会被调用多次并可能产生副作用,因此 React.StrictMode 触发这些方法两次以检查任何副作用。如果有任何副作用,将记录错误。 (副作用:在 method/component 之外更新的东西)

    • 构造函数
    • componentWillMount(或UNSAFE_componentWillMount)
    • componentWillReceiveProps(或UNSAFE_componentWillReceiveProps)
    • componentWillUpdate(或UNSAFE_componentWillUpdate)
    • getDerivedStateFromProps
    • shouldComponentUpdate
    • 渲染
    • setState 更新函数(第一个参数)
  2. 我们有可能使用了一些旧的 React 方法和 API,因此 React.StrictMode 识别并记录错误到控制台提及,该方法已过时。

  3. React.StrictMode 仅在开发模式下工作,因此无需担心生产。

结论: React.StrictMode 由 React 社区提供,帮助我们的应用程序跟踪更改,我们可以轻松自信地将我们的应用程序升级到新版本。