[英]Uncaught TypeError: Cannot read properties of undefined (reading 'questionText')
我收到一條錯誤消息,提示我的“questionText”無法讀取或未定義。 第一個代碼是我使用“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>
但這是一個非常混亂的代碼,所以我會使用第一個。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.