为什么我的 React 组件在初始加载时渲染两次? [英] Why is my react component rendering twice on initial load?

查看:31
本文介绍了为什么我的 React 组件在初始加载时渲染两次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

function First() {const [count,setCount]=useState(0)console.log("component first rendering")//这个日志记录发生了两次返回 (<div>第一个组件

)}

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

解决方案

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

<块引用>

根据此文档:

严格模式无法自动为您检测副作用,但它可以通过使它们更具确定性来帮助您发现它们.这是通过有意重复调用以下函数来完成的:

  • 类组件构造函数、render 和 shouldComponentUpdate 方法

  • 传递给 useState、useMemo 或 useReducer 的函数

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

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

希望有帮助:)

I have a functional component called (First)

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

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


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

when i initially run the application the console statement is logging twice why is it, It should have been logged only once, because i haven't explicitily updated the state.

解决方案

I've tried this out in code sandbox here and sure enough, it did render twice. This is because, in the index.js file, it uses 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

This is usually to help spot side effects only in the development environment. It does not apply to a production environment.

So if you don't want it to render twice, simply remove the <React.StrictMode> </ React.StrictMode> in the index.js file and it'll work normally.

Hope it helps :)

这篇关于为什么我的 React 组件在初始加载时渲染两次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆