React flushSync() 没有按预期工作。

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

React flushSync() isn't working as expected

问题

以下是您要翻译的内容:

"我清楚以下做法并不好。然而,我想知道为什么在我点击按钮后,如果我使用 flushSync(),这段代码片段不起作用。
当我说它不起作用时,我是指警报显示为“你好,!”并且在随后的点击中,它显示先前的状态而不是当前的状态。"

export default function FeedbackForm() {
  const [name, setName] = useState('');

  function handleClick() {
    flushSync(() => {
      setName(prompt('What is your name?'))
    })

    alert(`Hello, ${name}!`);
  }

  return (
    <button onClick={handleClick}>
      Greet
    </button>
  );
}
英文:

I am clear that the following is not a good practice. However, I would like to know why this snippet is not working after I click on the button if I'm using flushSync().
When I say that it is not working, I'm referring to the fact that the alert is showing "Hello, !" and during subsequent clicks, it shows the previous state instead of the current one.

export default function FeedbackForm() {
  const [name, setName] = useState(&#39;&#39;);

  function handleClick() {
    flushSync(() =&gt; {
      setName(prompt(&#39;What is your name?&#39;))
    })

    alert(`Hello, ${name}!`);
  }

  return (
    &lt;button onClick={handleClick}&gt;
      Greet
    &lt;/button&gt;
  );
}

答案1

得分: 3

在阅读了这里和那里之后,我得出了以下结论:

React 使用 flushSync() 强制更新DOM,但这并不意味着它会立即更新状态变量(name),因为我们知道,React 是异步更新状态的。

这种方法更适用于 如果你想从DOM中获取一些更新后的信息,但需要首先设置一个状态。

总之,文档建议只在绝对必要的情况下使用这种方法。

英文:

After reading here and there, I arrived at the following conclusion:

React forces the update of the DOM using flushSync(), but this doesn't mean it also updates the state variable (name) immediately because, as we know, React updates the state asynchronously.

This approach would be more suitable if you want to obtain some updated information from the DOM, but you need to set a state first.

Anyways, the documentation advises against using this method unless it is absolutely necessary.

huangapple
  • 本文由 发表于 2023年5月17日 20:43:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/76272246.html
匿名

发表评论

匿名网友

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

确定