在使用ReactJS中的useRef时,组件重新渲染计数不正确。

huangapple go评论78阅读模式
英文:

Component rerendering count is incorrect while using useRef in ReactJS

问题

我正在按照网上的教程学习useRef Hook,大部分情况下都运行正常,只是在打印2后无法继续正常工作。请告诉我我在这里做错了什么。

在示例代码中,我想使用useRef来计算组件的重新渲染次数。现在,如果您在输入框中输入一些内容,您会注意到它不会渲染出 2,但会打印出其他所有数字。

代码 -

const InputField = () => {
  const [val, setVal] = useState("");
  const comRef = useRef(1);

  useEffect(() => {
    comRef.current = comRef.current + 1;
  });

  return (
    <div className="fieldset-input-textbox">
      <input type="text" value={val} onChange={(e) => setVal(e.target.value)} />
      <div className="">
        This Component rendered {comRef.current}
        {`${comRef.current > 1 ? " times" : " time"}`}.
      </div>
    </div>
  );
};

export default InputField;

Code Sandbox链接 - https://codesandbox.io/s/busy-paper-f2qdhs?file=/src/InputField.js:54-542

英文:

I am following a tutorial from the web for learning useRef Hook, which works mostly fine except it is unable to print 2 though after that it behaves normally. Let me know what I am doing wrong here.

In the example code, I want to count the re-render of a component using useRef. Now if you type something in the input box you will notice it won't render 2 rest all numbers it will print.

Code -

const InputField = () =&gt; {
  const [val, setVal] = useState(&quot;&quot;);
  const comRef = useRef(1);

  useEffect(() =&gt; {
    comRef.current = comRef.current + 1;
  });

  return (
    &lt;div className=&quot;fieldset-input-textbox&quot;&gt;
      &lt;input type=&quot;text&quot; value={val} onChange={(e) =&gt; setVal(e.target.value)} /&gt;
      &lt;div className=&quot;&quot;&gt;
        This Component rendered {comRef.current}
        {`${comRef.current &gt; 1 ? &quot; times&quot; : &quot; time&quot;}`}.
      &lt;/div&gt;
    &lt;/div&gt;
  );
};

export default InputField;

Code Sandbox Link - https://codesandbox.io/s/busy-paper-f2qdhs?file=/src/InputField.js:54-542

答案1

得分: 0

你的根组件被包裹在 &lt;React.StrictMode&gt; 中,因此在开发过程中,React 会在初始挂载时将组件渲染两次,以帮助捕捉意外的不纯情况。

这会导致效果运行两次,因此在组件挂载后,comRef.current 变为 3。更改引用不会引发重新渲染,因此此新值在在文本字段中输入后才显示,这会更新 val 状态。然后,它将显示 3,接下来的效果将在此之后运行。

英文:

You have your root component wrapped in &lt;React.StrictMode&gt;, so during development, React will render the component twice for the initial mount to help catch accidental impurities.

This causes the effect to be run twice, so comRef.current becomes 3 after the component is mounted. Changing refs does not cause rerenders, so this new value is not shown until typing in the text field, which updates the val state. Then, it will display 3 and the next effect will run after that.

huangapple
  • 本文由 发表于 2023年7月14日 02:36:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/76682351.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定