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

React中useEffect依赖变化不触发,返回第1题时出现读取undefined错误

问题解决:React useEffect不触发与undefined读取错误

一、修复useEffect从第2题回退到第1题不执行的问题

问题原因

你的useEffect依赖数组存在错误:

  • 错误添加了setStep(useState返回的更新函数是稳定引用,无需加入依赖)
  • 遗漏了setCurrentQuestion(从context获取的函数,必须加入依赖,否则会因闭包问题导致使用旧的函数引用,无法正确更新context状态)

解决方案

修正useEffect的依赖数组,移除setStep并添加setCurrentQuestion:

useEffect(() => {
  console.log('step useeffet', step);
  if (step === 1) {
    setCurrentQuestion('Q1');
  } else if (step === 2) {
    setCurrentQuestion('Q2');
  } else if (step === 3) {
    setCurrentQuestion('Q3');
  } else if (step === 4) {
    setCurrentQuestion('Q4');
  }
}, [step, setCurrentQuestion]); // 修正后的依赖数组

二、修复"Cannot read properties of undefined (reading 'indexOf')"错误

问题原因

当currentQuestion无效或getQuestion返回undefined时,question?.options会是undefined,而Carbon的Dropdown组件要求items必须是数组,内部执行indexOf时会因undefined报错。

解决方案

  1. 确保question始终有默认值:在Step1组件中,给question设置默认对象,保证options是数组:
const question = getQuestion(currentQuestion) || { text: '', options: [] };
  1. 给Dropdown的items设置兜底数组:即使question?.options为undefined,也传入空数组避免报错:
<Dropdown
  ariaLabel="Dropdown"
  label="Select your best match"
  titleText={''}
  items={question?.options || []} // 添加兜底空数组
  onChange={(e: any) => console.log(e)}
  initialSelectedItem={'Government'}
  light={true}
/>
  1. 验证context中questions数据完整性:确保questions对象包含'Q1'到'Q4'的键,保证getQuestion能返回有效对象。

额外优化点

  • 简化updateStepIndex函数,当前逻辑中index === 4的判断是多余的(回退场景下index只会是1-3),可以直接写:
const updateStepIndex = (index: number) => {
  setStep(index);
};
  • 移除不必要的@ts-ignore注释,建议通过类型定义修复TypeScript报错,而不是忽略。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 17:40:28