gpt4 book ai didi

javascript - 为什么我的 react 组件在初始加载时渲染两次?

转载 作者:行者123 更新时间:2023-12-03 07:02:57 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Why is my React component is rendering twice?

(7 个回答)


6 个月前关闭。




我有一个名为(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


这通常是为了帮助仅在开发环境中发现副作用。它不适用于生产环境。
因此,如果您不希望它渲染两次,只需删除 <React.StrictMode> </ React.StrictMode>index.js文件,它会正常工作。
希望能帮助到你 :)

关于javascript - 为什么我的 react 组件在初始加载时渲染两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62324139/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com