如何使用useEffect和useState实现React组件首次渲染表格?
React组件中用useEffect和useState实现表格首次渲染的解决方案
1. 初始化State为数组
你当前的useState()未设置初始值,默认是undefined,后续调用map会直接抛出错误。必须把初始值设为空数组,确保数据未返回时也能安全调用数组方法:
const [tableData, setTableData] = React.useState([])
2. 理解useState的异步更新特性
你在setTableData后立即打印tableData显示undefined是正常现象——React的state更新是异步的,在同一个函数调用栈内,state不会立刻更新。如果要查看更新后的数据,可以:
- 在组件渲染阶段打印(比如return语句前添加
console.log(tableData)) - 新增监听
tableData变化的useEffect:useEffect(() => { console.log('更新后的tableData:', tableData) }, [tableData])
3. 实现表格渲染与状态处理
数据加载是异步过程,需要处理加载中和无数据的状态,同时修正代码中可能的拼写错误(比如adress应为address,item.is应为item.id):
return ( <div> {tableData.length === 0 ? ( <p>加载中...</p> ) : ( <table border="1"> <thead> <tr> <th>ID</th> <th>地址</th> {/* 根据实际数据结构添加更多表头 */} </tr> </thead> <tbody> {tableData.map(item => ( <tr key={item.id}> <td>{item.id}</td> <td>{item.address}</td> {/* 根据实际数据结构添加更多单元格 */} </tr> ))} </tbody> </table> )} </div> )
完整修改后的组件代码
import React, { useEffect, useState } from 'react' const Projects = () => { const [tableData, setTableData] = React.useState([]) const [loading, setLoading] = useState(true) useEffect(() => { fetch('https://script.google.com/macros/s/AKfycbzuKuSOUfd9IOsQobix0PnIRv28IB3uTx5KdpVoVeNe04g7QzXQeeCEbsHBxE5CYdEV8A/exec') .then((response) => response.json()) .then((response) => { setTableData(response['smr']) setLoading(false) }) .catch(err => { console.error('数据加载失败:', err) setLoading(false) }) }, []); if (loading) { return <div>加载中...</div> } return ( <div> {tableData.length === 0 ? ( <p>暂无数据</p> ) : ( <table border="1"> <thead> <tr> <th>ID</th> <th>地址</th> </tr> </thead> <tbody> {tableData.map(item => ( <tr key={item.id}> <td>{item.id}</td> <td>{item.address}</td> </tr> ))} </tbody> </table> )} </div> ) } export default Projects
内容的提问来源于stack exchange,提问作者Дмитрий Серебро
相关产品推荐
相关产品推荐

