gpt4 book ai didi

javascript - React 18,useEffect 在挂载时被调用两次

转载 作者:行者123 更新时间:2023-12-05 00:24:54 30 4
gpt4 key购买 nike

我有一个柜台并设置console.loguseEffect记录我的 state 中的所有更改,但 useEffect在安装时被调用两次。我正在使用 React v18.0.0 .这是 CodeSandbox我的项目和下面的代码:

import  { useState, useEffect } from "react";

const Counter = () => {
const [count, setCount] = useState(5);

useEffect(() => {
console.log("rendered", count);
}, [count]);

return (
<div>
<h1> Counter </h1>
<div> {count} </div>
<button onClick={() => setCount(count + 1)}> click to increase </button>
</div>
);
};

export default Counter;

最佳答案

此行为来自 React 18当你在 developmentStrict Mode .核心团队正在尝试实现这个功能,我们可以保留组件的 state即使在 unmount 之后. useEffect被调用两次与此功能有关。以下是他们在 doc 中所说的概述。 :

In the future, we’d like to add a feature that allows React to add and remove sections of the UI while preserving state.


With Strict Mode starting in React 18, whenever a component mounts in development, React will simulate immediately unmounting and remounting the component.


On the second mount, React will restore the state from the first mount. This feature simulates user behavior such as a user tabbing away from a screen and back, ensuring that code will properly handle state restoration.


⚠️ This only applies to development mode, production behavior is unchanged.


但是,如果您需要,例如在您想要 useEffect 的情况下的回调仅在 count 时执行更改,您可以使用 bool 值 ref使用 useRef添加一些额外的控件,如下所示:
import  { useState, useEffect, useRef } from "react";

const Counter = () => {
const firstRenderRef = useRef(true);
const [count, setCount] = useState(5);

useEffect(() => {
if(firstRenderRef.current){
firstRenderRef.current = false;
return;
}
console.log("rendered", count);
}, [count]);

return (
<div>
<h1> Counter </h1>
<div> {count} </div>
<button onClick={() => setCount( count + 1 )}> click to increase </button>
</div>
);
};

export default Counter;
上面的代码只有在 count 时才会记录。 production 的变化.在 developmentStrict Mode , 你会得到 one登录 mount而不是 two就像你以前一样,因为 if陈述。

关于javascript - React 18,useEffect 在挂载时被调用两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72238175/

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