React中如何将axios.get返回数据通过react-table渲染为表格并解决报错
问题根源
React Table 的 useTable Hook 规定传入的配置项中,渲染数据源对应的属性名固定为data,你代码中直接传入了自定义的状态名rounds,导致useTable无法读取到要渲染的数据源,尝试遍历undefined时就抛出了TypeError: Cannot read properties of undefined (reading 'forEach')错误。
修复方案
修改useTable的传参,将rounds赋值给data字段即可:
const { getTableProps, getTableBodyProps, headerGroups, rows, prepareRow, } = useTable({ columns, data: rounds })
可选优化
- 新增加载状态,避免请求返回前显示空白表格:
const ReviewRounds = () => { const [rounds, setRounds] = useState([]); const [loading, setLoading] = useState(true); // 新增加载状态 const fetchVids = () => { axios.get(process.env.REACT_APP_URL_All_ROUNDS) .then(res => { console.log("Rounds", res.data) setRounds(res.data) }) .catch(err => { console.error('评审轮次数据请求失败:', err) }) .finally(() => setLoading(false)) // 请求完成后关闭加载状态 } // ...其余原有代码 // 渲染前判断加载状态 if (loading) return <div>数据加载中,请稍候...</div> return ( // ...原有表格渲染逻辑 ) }
- 给axios请求新增异常捕获逻辑,避免接口报错时页面直接崩溃。
内容的提问来源于stack exchange,提问作者Paddyd101
相关产品推荐
相关产品推荐

