英文:
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 日志的截图
我尝试使用 memo
和 useCallback
(我知道它仅用于优化:))来避免可能会重置状态的重新渲染。
可能导致问题的原因是什么,如何修复?
提前感谢:)
编辑(添加了一个最小可复制示例):源码
英文:
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.
<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
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 <Form>
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论