简体   繁体   English

具有相同原始值的 React 钩子调用 setState 仍然会导致重新渲染

[英]React hooks call setState with same primitive value still cause re-render

I find that when I define a state with the value '1',我发现当我定义一个值为“1”的 state 时,

and set the state with the value '2' every time when I click a button,并在每次单击按钮时将 state 的值设置为“2”,

the first two times will cause re-render前两次将导致重新渲染

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

code: using react@17 without strict mode代码:使用没有严格模式的 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

I can understand the first re-render because the state changed to '2' from '1',我可以理解第一次重新渲染,因为 state 从“1”更改为“2”,

but I don't understand the second re-render但我不明白第二次重新渲染

I think this explains the anomaly very well:我认为这很好地解释了异常:

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.如果您将 State Hook 更新为与当前 state 相同的值,React 将在不渲染子节点或触发效果的情况下退出。 (React uses the Object.is comparison algorithm.) (React 使用 Object.is 比较算法。)

Note that React may still need to render that specific component again before bailing out.请注意,React 可能仍需要在退出之前再次渲染该特定组件。 That shouldn't be a concern because React won't unnecessarily go “deeper” into the tree.这不应该是一个问题,因为 React 不会不必要地 go “深入”到树中。 If you're doing expensive calculations while rendering, you can optimize them with useMemo如果您在渲染时进行昂贵的计算,您可以使用 useMemo 对其进行优化

Note the last paragraph.注意最后一段。 This is quoted directly from here .这是直接从这里引用的。

I think something missing in the code.我认为代码中缺少一些东西。 I checked on my end.我检查了我的结束。 it's working fine as per our expectations.按照我们的预期,它运行良好。

Thanks谢谢

import React from "react";
import "./styles.css";
import { useState } from "react";

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

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM