React报错Uncaught TypeError:无法读取undefined的questionText属性求助
问题分析:无法读取undefined的questionText属性
错误场景
报错信息:Uncaught TypeError: Cannot read properties of undefined (reading 'questionText')
核心原因
- 数组索引越界:你定义的
questions数组仅包含1个问题(索引为0),但组件的handleClick函数中判断条件是questionIndex < 9。当用户点击选项后,questionIndex会递增到1,此时questions[1]是undefined,自然无法读取questionText属性。 - 缺少空值保护:代码中直接访问
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
相关产品推荐
相关产品推荐

