React状态在渲染之间被重置为先前的值。

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

React state gets reset to previous value between renders

问题

我在按钮的点击事件中更新状态(一个数组),对于状态数组中的所有元素,一切都运行正常,除了最后一个元素,当快速更新它时,它会重置状态到旧值。

<Button
      icon={<IconDeleteStroked />}
      type="danger"
      onClick={() => {
      Toast.success("Table deleted!");
      props.setTables((prev) => {
      return prev
           .filter((e) => e.id !== i)
           .map((e, idx) => ({ ...e, id: idx }));
      });
       setTableActiveKey("");
      }}
 ></Button>

setTables 从父组件传递下来,我通过在 useEffect 中记录它们来跟踪 tables,您可以在这里看到它被正确地更新为 [],然后到 [{...}] useEffect 日志的截图

我尝试使用 memouseCallback(我知道它仅用于优化:))来避免可能会重置状态的重新渲染。

可能导致问题的原因是什么,如何修复?

提前感谢:)

编辑(添加了一个最小可复制示例):源码

英文:

I'm updating state(an array) onClick of a button, everything works fine for all the elements in the state array except for the last one which when updated quickly reset the state to its old value.

 &lt;Button
      icon={&lt;IconDeleteStroked /&gt;}
      type=&quot;danger&quot;
      onClick={() =&gt; {
      Toast.success(&quot;Table deleted!&quot;);
      props.setTables((prev) =&gt; {
      return prev
           .filter((e) =&gt; e.id !== i)
           .map((e, idx) =&gt; ({ ...e, id: idx }));
      });
       setTableActiveKey(&quot;&quot;);
      }}
 &gt;&lt;/Button&gt;

setTables gets passed down from a parent component, and I'm tracking the tables by logging them in a useEffect
here you can see it get correctly updated to [] and then to [{...}]screenshot of useEffect logs

I tried using memo and useCallback( ik it's only for optimization:') ) to avoid rerenders that might reset the state.

What might be causing the problem and how can it be fixed?

Thanks in advance:)

Edit (added a minimal reproducible example): src

答案1

得分: 1

这是因为您的<Form>onChange在单击删除按钮时触发,并在调用props.setTables(updatedTables);时覆盖了已删除的表格更新,因为其中对tables的引用不知道已删除的表格。

英文:

It's because your &lt;Form&gt; onChange is triggering when you click the delete button, and overwriting the deleted table update when it calls props.setTables(updatedTables);, since the references to tables in there doesn't know about the deleted table.

huangapple
  • 本文由 发表于 2023年6月26日 06:21:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/76552634.html
匿名

发表评论

匿名网友

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

确定