是否建议在切换或反应更改事件时使用以前的状态?

发布于 2025-01-17 17:33:31 字数 617 浏览 0 评论 0原文

我对 onChange 回调进行了更改,以使用状态而不是 React 的更改事件。这个更改是推荐的并且符合约定,还是使用 React 的事件更好?

const Toggle: React.FC = () => {
  const { on, setOn } = useContext(AppContext);
  const isOn: boolean = on.key === 'on';

  const handleToggle = (checked: boolean) => {
    const key: string = checked ? 'on' : 'off';

    setOn(key);
  };

  return (
    <Toggle
      name="toggle"
      type="checkbox"
      checked={isOn}
      onChange={(e: any) => handleToggle(e.target.checked)} // before
      onChange={() => handleToggle(!isOn)}                  // after
    />
  );
};

I have made a change to the onChange callback to use the state rather than the change event from React. Is this change recommended and in line with conventions or is it better to use the event from React instead?

const Toggle: React.FC = () => {
  const { on, setOn } = useContext(AppContext);
  const isOn: boolean = on.key === 'on';

  const handleToggle = (checked: boolean) => {
    const key: string = checked ? 'on' : 'off';

    setOn(key);
  };

  return (
    <Toggle
      name="toggle"
      type="checkbox"
      checked={isOn}
      onChange={(e: any) => handleToggle(e.target.checked)} // before
      onChange={() => handleToggle(!isOn)}                  // after
    />
  );
};

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

只为一人 2025-01-24 17:33:31

理想情况下,您都不会使用和setonreact.usestate()挂钩的结果,它均不会使用。 https://reaectjs.org/docs/hooks-reference.html#functional-updates“ rel =” nofollow noreferrer“>功能更新。取而代之的是这样的东西:

onChange={() => setOn(oldValue => oldValue ? 'off' : 'on')}

使用功能更新在可能的种族条件下 - 例如,如果用户在某些不太可能的巧合中,在React有机会处理状态更新和重新渲染之前,用户单击两次切换怎么办?两个(或更多)快速点击的结果可能会产生不正确的行为 - React将使用相同的值来连续多次更新状态,从本质上导致多次点击行为(将输入切换但不是off再次),而不是正确切换上的输入,然后 off ,然后 on 等

。更新以按顺序处理要处理的更新,以确保每个更新都可以访问由上一个更新产生的真实,更新的状态。因此,即使用户在微秒内单击两次切换输入,三次,十二次,输入端状态也将如预期的那样。

编辑:我将这个示例放在一起证明为什么这很重要及其影响。仔细观察计数器按钮的OnClick处理程序,并注意它们如何匹配我们确定的三种可能的方法。当您单击“触发三个快速单击下面的所有计数按钮”按钮时,就可以做到这一点。但是,观察 功能更新方法给出了这种情况的适当终端状态 - 它会增加+3,因为它单击了三次,而其他两个计数器仅增加+1。

Ideally you would use neither, assuming that on and setOn are the result of a React.useState() hook which supports functional updates. Instead, something like this:

onChange={() => setOn(oldValue => oldValue ? 'off' : 'on')}

Using the functional update behavior avoids any kind of possible race conditions - for example, what if by some unlikely coincidence the user clicks the toggle twice rapidly before React has a chance to process state updates and re-render? The result of two (or more) rapid clicks could possibly give improper behavior - React would use the same value for updating state multiple times in a row, essentially causing multiple clicks to behave as one (toggling the input on but not off again) instead of properly toggling the input on and then off and then on etc.

Functional updates enqueue the updates to be processed in order, in such a way that each update is guaranteed to have access to the true, updated state that resulted from the previous update. So even if the user clicked the toggle input twice, three time, a dozen times in a microsecond, the input end state will be as expected.

Edit: this example I put together demonstrates why this is important and the impact it has. Look closely at the onClick handlers of the counter buttons, and note how they match the three possible approaches we have identified. When you click the "Trigger three rapid clicks on all counter buttons below" button, it does just that. But observe how only the functional update approach gives the proper end state for this situation - it increments by +3, because it was clicked three times, while the other two counters only increment by +1.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文