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

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

问题描述

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

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>
    )
}

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

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.

根据此文档:

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

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:

  • 类组件的构造函数,呈现器和shouldComponentUpdate方法

  • Class component constructor, render, and shouldComponentUpdate methods

传递给useState,useMemo或useReducer的函数

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.

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

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.

希望它会有所帮助:)

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

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