You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 15:06:03