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报错。
解决方案
- 确保
question始终有默认值:在Step1组件中,给question设置默认对象,保证options是数组:
const question = getQuestion(currentQuestion) || { text: '', options: [] };
- 给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} />
- 验证context中questions数据完整性:确保
questions对象包含'Q1'到'Q4'的键,保证getQuestion能返回有效对象。
额外优化点
- 简化
updateStepIndex函数,当前逻辑中index === 4的判断是多余的(回退场景下index只会是1-3),可以直接写:
const updateStepIndex = (index: number) => { setStep(index); };
- 移除不必要的
@ts-ignore注释,建议通过类型定义修复TypeScript报错,而不是忽略。
内容的提问来源于stack exchange,提问作者Raj
相关产品推荐
相关产品推荐

