gpt4 book ai didi

javascript - React hooks 使用相同的原始值调用 setState 仍然会导致重新渲染

转载 作者:行者123 更新时间:2023-12-05 01:32:03 24 4
gpt4 key购买 nike

我发现当我定义一个值为“1”的状态时,

每次单击按钮时都将状态设置为“2”,

前两次会导致重新渲染

重现演示:https://codesandbox.io/s/sweet-brattain-ys11d

代码:在没有严格模式的情况下使用 react@17

import { useState } from "react";

export default function App() {
const [a, setA] = useState("1");
console.log("render", a);
return (
<button
onClick={() => {
setA("2");
}}
>
{a}
</button>
);
}

// log:
// render 1
// render 2
// render 2

我能理解第一次重新渲染是因为状态从'1'变成了'2',

但我不明白第二次重新渲染

最佳答案

我认为这很好地解释了异常:

If you update a State Hook to the same value as the current state, React will bail out without rendering the children or firing effects. (React uses the Object.is comparison algorithm.)

Note that React may still need to render that specific component again before bailing out. That shouldn’t be a concern because React won’t unnecessarily go “deeper” into the tree. If you’re doing expensive calculations while rendering, you can optimize them with useMemo

注意最后一段。这是直接引用自 here .

关于javascript - React hooks 使用相同的原始值调用 setState 仍然会导致重新渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65803394/

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