我在useState中发现错误了吗?或者我不了解它是如何工作的



我有一个状态更新程序,它从graphQL查询中获取数据对象,并将其重新组织为状态中的单个数组,删除返回的任何未定义||0长度数组的数据。

useEffect(() => {
if (data !== undefined) {
var e: Group[]
var arrays = Object.values(data) as Group[][]
for (e of arrays) {
if (checkEmptyArray(e)) {
console.log(e)
// don't remove this const, code doesn't work without it.
const destructured = [...e]
setDataArray(prevState => [...prevState, ...destructured])
}
}
}
}, [data])

工作完全正常。一旦用...e替换...destructured,它就无法工作。

这对我来说很奇怪。是虫子吗?或者我不明白什么?

所以。。。我想正在发生的事情是这样的;当你使用e时,它会被";对于(e个阵列(";在";prevState=>[…prevState,…e]";得到适当的评价,而";const destructured=[…e]";创建一个新对象,每次传递给函数。

旁注;你确定要在循环中调用setDataArray((吗?我猜这会调用多个重渲染。

最新更新