预期无限重新渲染,但没有发生。

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

Expected infinite re-rendering but didn't happen

问题


import React, { useState, useEffect } from "react";
export default function Example() {
  const [count, setCount] = useState(0);
  const [tmp, setTmp] = useState(0);
  useEffect(() => {
    document.title = `You clicked ${count} times`;
    setTmp(count);
    console.log(tmp);
  });
  return (
    <div>
      <p>
        You clicked {count} times and temp is {tmp}
      </p>
      <button onClick={() => setCount(count + 1)}>Click me</button>
    </div>
  );
}
英文:

import React, { useState, useEffect } from &quot;react&quot;;
export default function Example() {
  const [count, setCount] = useState(0);
  const [tmp, setTmp] = useState(0);
  useEffect(() =&gt; {
    document.title = `You clicked ${count} times`;
    setTmp(count);
    console.log(tmp);
  });
  return (
    &lt;div&gt;
      &lt;p&gt;
        You clicked {count} times and temp is {tmp}
      &lt;/p&gt;
      &lt;button onClick={() =&gt; setCount(count + 1)}&gt;Click me&lt;/button&gt;
    &lt;/div&gt;
  );
}


After reading this I expected this to cause infinite re-render because a state tmp is getting changed inside the useEffect but it didn't, can someone please help what might be the cause?

答案1

得分: 3

React的setter在值没有改变的情况下会忽略设置。重复调用setTmp(0)不会触发新的渲染。将其更改为setTmp(n => n+1),你将获得你所期望的无限循环。

英文:

React setters ignore the set if the value didn't change. Repeatedly calling setTmp(0) will not trigger new renders. Change it to setTmp(n =&gt; n+1) and you will get the infinite loop you're looking for.

huangapple
  • 本文由 发表于 2023年7月27日 22:09:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/76780590.html
匿名

发表评论

匿名网友

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

确定