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

React项目报TypeError: action.value is undefined错误是什么原因?

问题原因及修复方案

你遇到的action.value未定义错误由两个问题共同导致:

1. 未判断questions是否有值就直接dispatch

你封装的useQuestions钩子中,questions状态初始值为undefined,而Quiz组件的useEffect监听questions变化时,没有做非空判断就直接dispatch:

// 原代码存在问题
useEffect(() => {
  dispatch({
    type: "questions",
    value: questions,
  });
}, [questions]);

第一次触发该useEffect时,questions还没有从Firebase拿到数据,值为undefined,导致reducer的questions分支中调用action.value.forEach时报错。

修复方案二选一:

  • 修改useQuestions中questions的初始值为空数组:
    const [questions, setQuestions] = useState([]);
    
  • 或者在dispatch前添加非空判断:
    useEffect(() => {
      if (Array.isArray(questions) && questions.length > 0) {
        dispatch({
          type: "questions",
          value: questions,
        });
      }
    }, [questions]);
    

2. answer类型action的参数名不匹配

你在handleAnswareChange中dispatch的参数字段为QuestionsID,但reducer中取值用的是action.questionID,字段名大小写、拼写都不对应,后续也会触发数组下标读取错误:

// 原代码存在问题
dispatch({
  type: "answer",
  QuestionsID: currentQuestions, // 字段名和reducer不匹配
  optionIndex: index,
  value: e.target.checked,
});

修复方案:将字段名修改为和reducer一致:

dispatch({
  type: "answer",
  questionID: currentQuestions,
  optionIndex: index,
  value: e.target.checked,
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 06:36:02