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

React报错Uncaught TypeError:无法读取undefined的questionText属性求助

问题分析:无法读取undefined的questionText属性

错误场景

报错信息:Uncaught TypeError: Cannot read properties of undefined (reading 'questionText')

核心原因

  1. 数组索引越界:你定义的questions数组仅包含1个问题(索引为0),但组件的handleClick函数中判断条件是questionIndex < 9。当用户点击选项后,questionIndex会递增到1,此时questions[1]是undefined,自然无法读取questionText属性。
  2. 缺少空值保护:代码中直接访问questions[questionIndex].questionText,没有处理questions[questionIndex]为undefined的情况,一旦索引超出数组长度就会触发报错。

修复方案

1. 动态判断数组长度,避免硬编码索引

将handleClick中的判断条件从固定的9改为基于数组长度的动态值,适配任意数量的题目:

const handleClick = (isCorrect) => {
  if (questionIndex < questions.length - 1) {
    if (isCorrect) {
      setScore((score) => score + 100);
    }
    setQuestionIndex((prevIndex) => prevIndex + 1);
  } else {
    if (isCorrect) {
      setScore((score) => score + 100);
    }
    setShowQuestionsPagePop(false);
    setShowFinalPage(true);
  }
};

2. 添加可选链操作符做空值保护

在渲染部分使用可选链?.,防止索引无效时直接抛出错误,同时可以添加兜底内容:

return (
  <Card>
    <h1 className="question">{questions[questionIndex]?.questionText || '加载中...'}</h1>

    <div className="answers">
      {questions[questionIndex]?.answers?.map((answer, index) => (
        <div 
          className="answer"
          key={index}
          onClick={() => handleClick(answer.correctAnswer)}
        >
          <p>{answer.answerText}</p>
        </div>
      )) || <p>暂无选项</p>}
    </div>
  </Card>
)

3. (可选)补全questions数组

如果业务逻辑确实需要10道题(对应原代码的questionIndex <9),需要给questions数组补充足够的问题对象,确保每个索引都有对应的问题数据。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 05:06:25