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

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

React state gets reset to previous value between renders

问题

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

  1. <Button
  2. icon={<IconDeleteStroked />}
  3. type="danger"
  4. onClick={() => {
  5. Toast.success("Table deleted!");
  6. props.setTables((prev) => {
  7. return prev
  8. .filter((e) => e.id !== i)
  9. .map((e, idx) => ({ ...e, id: idx }));
  10. });
  11. setTableActiveKey("");
  12. }}
  13. ></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.

  1. &lt;Button
  2. icon={&lt;IconDeleteStroked /&gt;}
  3. type=&quot;danger&quot;
  4. onClick={() =&gt; {
  5. Toast.success(&quot;Table deleted!&quot;);
  6. props.setTables((prev) =&gt; {
  7. return prev
  8. .filter((e) =&gt; e.id !== i)
  9. .map((e, idx) =&gt; ({ ...e, id: idx }));
  10. });
  11. setTableActiveKey(&quot;&quot;);
  12. }}
  13. &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:

确定