未捕获的类型错误:无法读取未定义的属性(读取"问题文本")



我得到一个错误消息,我的"questionText"无法读取或未定义。第一个代码是我使用"questionText"第二个代码是我想拖拽它的地方。是不是我做错了什么,让他看不懂了?如果你还需要什么,就写信。我需要删除一些代码,因为StackOverflow不想要那么多代码:(.

import React from 'react'
import Card from './Card'
import "./Question.css"
const Question = ({
questionIndex,
setQuestionIndex,
questions,
setShowQuestionsPagePop,
setShowFinalPage,
score,
setScore,
}) => {
const handleClick = (isCorrect) => {
if (questionIndex < 9) {
if (isCorrect) {
setScore((score) => score += 100);
}
setQuestionIndex((prevIndex) => prevIndex + 1);
} else {
if (isCorrect) {
setScore((score) => (score += 100));
}
setShowQuestionsPagePop(false);
setShowFinalPage(true);
}
};

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>
))}
</div>
</Card>
)
}
export default Question
export const questions = [
{
questionText: "How long is an Olympic swimming pool (in meters)",
answers: [
{
answerText: "50",
correctAnswer: true,
},
{
answerText: "60",
correctAnswer: false,
},
{
answerText: "75",
correctAnswer: false,
},
{
answerText: "100",
correctAnswer: false,
},
],
},
];

您可以使用可选的链接,这使您能够读取对象的属性,如果它存在,否则将返回undefined,因此您的代码不会中断,尝试如下:

<h1 className="question">{questions[questionIndex]?.questionText}</h1>

另一个选择是手动检查该属性是否存在并有一个值,因此您可以这样做:

<h1 className="question">{questions && questions[questionIndex] && question[index].questionText && questions[questionIndex].questionText}</h1>

但是它是一个非常混乱的代码所以我将使用第一个