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

使用useState存储GET请求数据时出现TypeError问题求助

问题排查与解决方案

核心错误原因

  • 你的questionArray初始状态应该是空数组(比如const [questionArray, setQuestionArray] = useState([])),组件挂载时第二个useEffect会先因为questionArray的初始空值执行一次,此时questionArray[0]是undefined,直接访问.question就会抛出类型错误。
  • setQuestionArray是异步操作,调用后立刻console.log(questionArray)看到旧值是React useState的正常特性,和useLocation无关。

分步修复方案

1. 增加空值判断,避免访问undefined属性

修改监听questionArray的useEffect,先确认数组有有效内容再取值:

useEffect(() => { 
    // 先判断数组是否有元素,再访问内部属性
    if (questionArray.length > 0) {
        setQuestion(questionArray[0].question)
    }
}, [questionArray])

2. 补充参数校验,避免无效API请求

虽然当前错误和这个无关,但为了防止location.state为空导致请求失败,要先校验参数:

const getQuiz = async () => {
    try{
        const categoryName = location.state?.name
        const difficulty = location.state?.difficulty

        // 参数缺失时终止请求并提示
        if (!categoryName || !difficulty) {
            console.error('缺少分类或难度参数')
            return
        }

        let response = await axios.get(`https://the-trivia-api.com/api/questions?categories=${categoryName}&limit=10&difficulty=${difficulty}`)
        let arrayDataResponse = await response.data

        setQuestionArray(arrayDataResponse)

    } catch(err){
        console.log(err)
    }
}

3. 正确看待useState的异步特性

调用setQuestionArray后立刻console.log(questionArray)看到空数组是正常的,React会批量更新状态,不会同步修改state值。如果要查看更新后的state:

  • 可以把console.log(questionArray)写在组件顶层(渲染函数中)
  • 或者放在监听questionArray的useEffect里

总结

当前错误和useLocation无关,完全是未处理questionArray为空的情况导致的。加上空值判断即可解决问题,补充参数校验能让代码更健壮。

内容的提问来源于stack exchange,提问作者here2learn

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 19:15:11