React,使用setState会导致无限循环错误



我正在学习React入门课程,只是想完成一些类似于我在培训中看到的东西。我试图从API端点提取数据,对数据做一点改变,然后使用setState来更新将保存新数据集的变量的值。

API返回如下的数据集:

{
"site1": [
"device-a01",
"device-a02",
"device-b01",
"device-b02"
],
"site2": [
"device-a01",
"device-a02",
"device-b01",
"device-b02",
"device-c01",
"device-c02"
]
}

我需要遍历这个对象并创建一个数组变量,它应该是这样的:

const tableData = [
[
"site1", "device-a01", 
"site1", "device-a02",
"site1", "device-b01", 
"site1", "device-b02",
"site2", "device-a01", 
"site2", "device-a02",
"site2", "device-b01", 
"site2", "device-b02",
"site2", "device-c01", 
"site2", "device-c02"
]

我代码:

import React from "react"
const [dataSet2, setDataSet2] = React.useState([])
const [tableData, setTableData] = React.useState([])
React.useEffect(() => {
async function getData() {
const res = await fetch("https://url.com/api/devices/")
const data = await res.json()
// console.log(JSON.stringify(data))
setDataSet2(data)
}
getData()
},[])

Object.entries(dataSet2).map(([key, value]) => {
value.map(hub => {
buildTableData(key, hub)
})
})
function buildTableData(key, value) {
// console.log(key, value)
const hubValue = key + "," + value
console.log(hubValue) // prints the data to the console as i need it to be.
// this causes the infinit loop error
setTableData( prevData => ({
...prevData,
hubValue
}))
}

我发现了一些关于这个无限循环错误的文章,但它们是关于在事件处理程序(示例)中调用setState,不确定它是否与我想做的事情有关,如果是的话,那么我不知道如何在我的代码中修复它。

您需要在useEffect中构建表数据。我建议你准备好所有的数据,并在最后更新setDataSet2setTableData:

import React from "react"
const [dataSet2, setDataSet2] = React.useState([])
const [tableData, setTableData] = React.useState([])
function buildTableData(key, value) {
// console.log(key, value)
const hubValue = key + "," + value
console.log(hubValue) // prints the data to the console as i need it to be.
return {
...prevData,
hubValue
}
}
React.useEffect(() => {
async function getData() {
const res = await fetch("https://url.com/api/devices/")
const data = await res.json()

const _tableData = Object.entries(data).map(([key, value]) => {
return value.map(hub => buildTableData(key, hub)) // here is the fix
})

setTableData(_tableData);
setDataSet2(data);
}
getData()
},[])

我会尝试这样做:

import React from "react"
const [dataSet2, setDataSet2] = React.useState([])
const [tableData, setTableData] = React.useState([])
React.useEffect(() => {
fetch("https://url.com/api/devices/").then(res => setDataSet2(res.data))
}, [])
React.useEffect(() => {
if (!tableData) {
let results = []
Object.entries(dataSet2).map(([key, value]) => {
return value.map(hub => {
results.push(key)
results.push(hub)
})
})
setTableData(results)
}
}, [dataSet2])

相关内容

  • 没有找到相关文章

最新更新