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

React项目启动报错:Cannot read properties of undefined (reading 'correctAnswer')

排查线索:Uncaught TypeError: Cannot read properties of undefined (reading 'correctAnswer')

这个报错的核心原因是调用shuffleAnswers时传入了undefined,导致函数内部试图访问undefined.correctAnswer失败。以下是具体排查方向:

1. 初始状态的致命问题

你的initialState里同时定义了questions: []和answers: shuffleAnswers(questions[0])——此时questions是空数组,questions[0]就是undefined,直接传入shuffleAnswers必然触发报错。

临时修复:把初始answers设为空数组,等LOADED_QUESTIONS动作触发后再生成答案列表:

const initialState = {
  currentQuestionIndex: 0,
  questions:[],
  showResults: false,
  answers: [], // 改为空数组
  currentAnswer: "",
  correctAnswerCount: 0,
};

2. 检查questions数据导入是否正常

确认../../data导出的是符合预期的非空数组:

  • 在quiz.js开头添加console.log(questions),查看控制台输出是否为包含correctAnswer和incorrectAnswers字段的问题数组。
  • 如果输出是空数组或undefined,说明数据文件路径错误、导出格式不对,或者数据还没异步加载完成(如果是异步获取的话)。

3. 验证normalizeQuestions的输出

在LOADED_QUESTIONS分支里,确认normalizedQuestions是正确格式化的非空数组:

  • 可以在const normalizedQuestions = normalizeQuestions(action.payload)后添加console.log(normalizedQuestions),检查每个元素是否有correctAnswer和incorrectAnswers。
  • 如果normalizedQuestions为空,或者元素字段缺失,shuffleAnswers(normalizedQuestions[0])同样会传入undefined导致报错。

4. 处理NEXT_QUESTION中的边界情况

在NEXT_QUESTION分支里,调用shuffleAnswers(state.questions[currentQuestionIndex])前,先判断目标问题是否存在:

const answers = showResults
  ? []
  : state.questions[currentQuestionIndex] 
    ? shuffleAnswers(state.questions[currentQuestionIndex])
    : [];

避免因currentQuestionIndex越界或questions未加载完成导致传入undefined。

内容的提问来源于stack exchange,提问作者k.b

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 07:09:52