我觉得这应该很简单,但我一直在努力解决这个问题,希望得到一些帮助。
我正在尝试从使用 Axios 获取的数据表中的字段生成下拉列表。数据表加载和渲染得很好,但 React 无法将列表识别为数组,因此无法映射项目。数据表和列表都是在同一个函数中同时生成并存储在状态中的。
下面是我的代码。非常感谢任何有关如何执行此操作的建议。谢谢:
import React, {useState, useEffect} from 'react'
import db from './db.js' //<--I have my axios db connection in a seperate file
function App() {
const [industryData, setIndustryData] = useState([]) //
const [industryList, setIndustryList] = useState([]) //<--This is the list I want
const getData= async(req, res)=>{
const response = await db.get('/getTable/industries')
const data = response.data;
console.log(data) // <--Data loads fine
setIndustryData(data) // <--Data renders fine
//I want to get a dropdown list from one of the fields in the data above
let list = new Set()
industryData.forEach(row=>{
list.add(row.industry)
})
console.log(list) //<---this is empty for some reason.
setIndustryList(list) //<--This is empty.
}
useEffect(()=>{
getData()
},[])
return (
<div className="App">
//This is the dropdown I want but it's not working
<select>
{industryList.map(item=>( //<---React doesn't recognize this object
<option key={industryList.indexOf(item)}>{item}</option>
))}
</select>
//But rendering the original data table works. But I don't want to do this because I don't get unique values. I need a set. Also it's just cleaner to use a list than an entire data set.
<select>
{industryData.map(item=>( //<---This works fine
<option key={industryData.indexOf(item)}>{item.industry}</option>
))}
</select>
</div>
);
}
export default App;
看起来问题可能与
getData
函数的异步性质有关。当您调用 setIndustryList(list)
时,它可能不会立即更新 industryData
。你可以做的是,在getData
而不是industryData.forEach
中,你可以从data.foreach
获取数据。这是您可以使用的更新后的 getData
功能。
const getData= async(req, res)=>{
const response = await db.get('/getTable/industries')
const data = response.data;
console.log(data) // <--Data loads fine
setIndustryData(data) // <--Data renders fine
//I want to get a dropdown list from one of the fields in the data above
let list = new Set()
data.forEach(row=>{
list.add(row.industry)
})
console.log(list) //<---this is empty for some reason.
setIndustryList(list) //<--This is empty.
}