gpt4 book ai didi

javascript - react : why is the state returned from useState stays the same when the initializer function gets called on every re-render?

转载 作者:行者123 更新时间:2023-12-04 13:12:21 25 4
gpt4 key购买 nike

这是现场演示:https://codesandbox.io/s/strange-bash-qj7ld?file=/src/App.js

所以我有这样一个组件

const fn = () => {
console.log("useState");
return ["string"];
};

export default function App() {
const [counter, setCounter] = useState(0);

const [nonprimitive, setNonprimitive] = useState(fn());

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

return (
<>
<button onClick={() => setCounter(counter + 1)}>Counter {counter}</button>
<div>{nonprimitive[0]}</div>
</>
);
}

每次我点击按钮,计数器都会增加并且组件会重新渲染。然后再次调用fn(),返回一个数组。 useEffectnonprimitive 发生变化时被触发。我有两个问题:

  1. 为什么 useEffect 只触发一次,而不是每次后续调用都触发? nonprimitive 是一个数组,它是一个非原始类型,因此即使其中的字符串项保持不变,每次也应该不同。看起来 React 正在做一些深入的比较。
  2. 为什么每当组件重新呈现时 useState 都会打印两次?即 console.log("useState"); 当我按下按钮时 fn 被调用两次。

最佳答案

why is that useEffect gets triggered only once, not for every subsequent calls? nonprimitive is an array, which is a non primitive type, so it should be different every time even when the string item inside of it stays the same. It seems like React is doing some deep comparison under the hood.

整点useState是在组件的渲染中持久化值。您的组件第一次呈现时,useState(fn())被称为 nonprimitive获取值 ["string"] .在后续渲染中,useState(fn())再次被调用(因为毕竟它仍然是一个标准的函数调用,所以记录再次发生),但是 React 知道这不是你的第一次渲染,所以它丢弃了参数(fn 的返回值)而是返回先前存储的值,该值在引用上是相同的。

如果您不希望 React 在每次渲染时调用您的初始状态创建(例如,如果您的初始状态非常复杂或计算起来非常耗时),您可以向它传递一个它只会调用的函数初始渲染。

const [nonprimitive, setNonprimitive] = useState(() => fn());

在您的情况下,由于初始状态已经包装在一个函数中,您可以等效地编写

const [nonprimitive, setNonprimitive] = useState(fn);

Why is the useState gets printed out twice whenever the component re-renders? i.e. console.log("useState"); inside fn gets called twice when I hit the button.

如果您查看 index.js,您会注意到您的 App组件包裹在 <React.StrictMode> 中. React strict mode将有意多次运行某些渲染,以帮助您捕获代码中的副作用和钩子(Hook)违规。

关于javascript - react : why is the state returned from useState stays the same when the initializer function gets called on every re-render?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63768296/

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