React状态返回空值问题:useEffect获取API数据后访问属性报错
解决React useEffect获取API数据时的State访问错误
问题根源
- 数据结构误用:你初始化的
questions是数组,API返回的data.results同样是包含多个问题的数组——数组本身没有category属性,只有数组内的单个问题对象才拥有该属性,直接写questions.category必然报错。 - 未处理加载间隙:组件首次渲染时
questions是空数组,此时强行访问不存在的属性会触发错误,必须在数据加载完成前做状态判断。
解决方案
1. 正确访问数组内的数据
如果要显示单个问题(比如第一个),需先判断数组非空,再通过questions[0].category访问;如果要展示所有问题,用map遍历数组即可。
2. 添加加载状态处理
新增一个loading状态,在数据请求完成前显示加载提示,避免空数组导致的渲染错误。
修改后的代码示例
export default function Quiz(props) { const [questions, setQuestions] = React.useState([]) const [loading, setLoading] = React.useState(true) // 新增加载状态 React.useEffect(() => { fetch("https://opentdb.com/api.php?amount=10") .then(res => res.json()) .then(data => { setQuestions(data.results) setLoading(false) // 请求完成后关闭加载状态 }) .catch(err => { console.error("请求失败:", err) setLoading(false) // 请求失败也关闭加载状态,避免一直加载 }) }, []) // 加载状态时显示提示 if (loading) { return <div>加载中...</div> } // 数据为空时显示提示 if (questions.length === 0) { return <div>暂无题目数据</div> } return ( <div> {/* 显示第一个问题的分类 */} <div className="quiz--question"> <h1>{questions[0].category}</h1> </div> {/* 或者遍历所有问题显示(可取消注释使用) */} {/* <div className="quiz--questions"> {questions.map((question, index) => ( <div key={index} className="quiz--question"> <h2>{question.category}</h2> <p>{question.question}</p> </div> ))} </div> */} </div> ) }
额外说明
useEffect的空依赖数组确保请求仅在组件首次渲染时执行一次,符合你的需求。- 加上
catch捕获请求错误,避免网络问题导致组件一直处于加载状态。 - 遍历数组时建议使用问题的唯一标识作为
key(若API返回),示例中用index是简化方案。
内容的提问来源于stack exchange,提问作者itsoverkaiba
相关产品推荐
相关产品推荐

