React:为什么变量仅首次渲染有定义,后续渲染就变为undefined?
问题原因
- React 的
setState是异步批量更新机制,执行setQuestions(data)后无法在当前作用域同步拿到更新后的questions状态,此时读取的仍是初始空数组,questions[0]自然为 undefined then()需要接收回调函数作为参数,你写的then(setCurrent(questions[0]))是同步执行了setCurrent,没有等待前面的 fetch 请求完成- 接口返回的根结构是包含
questions字段的对象,直接把整个返回结果赋值给questions状态的话,状态里存的不是题目数组,而是外层的包裹对象,无法通过下标取到对应题目 - 首次渲染时接口请求尚未返回,
current为初始的 undefined,直接访问current['answers']会抛出运行时错误
修复后的完整代码
import React, { useEffect, useState } from 'react' export default function Answers() { const [questions, setQuestions] = useState([]) const [current, setCurrent] = useState() useEffect(() => { fetch('http://localhost:8000/questions') .then(res => res.json()) .then(data => { // 从返回结果里取出题目数组再赋值 const questionList = data.questions setQuestions(questionList) // 直接用接口返回的数据赋值,不依赖刚更新的state setCurrent(questionList[0]) }) }, []) // 空值判断,数据加载完成前显示加载状态,避免空值报错 if (!current) return <div>加载中...</div> return ( <div> <ul> {console.log(current['answers'])} {/* 遍历数组时要加唯一key,这里用下标做临时演示,实际业务建议用题目id做key */} {current['answers'].map((item, index) => <li key={index}>{item}</li>)} </ul> </div> ) }
内容的提问来源于stack exchange,提问作者ryanvb92
相关产品推荐
相关产品推荐

