【发布时间】:2020-12-31 11:46:34
【问题描述】:
我正在尝试读取 JSON 文件并尝试将其传递给组件,但是我收到此错误,TypeError: Cannot read property 'map' of undefined 而且我似乎找不到问题所在。
这是我创建的代码:
export default function Questions() {
const [currentQuestion, setCurrentQuestion] = useState(0);
const [showScore, setShowScore] = useState(false);
const [score, setScore] = useState(0);
const quizQuestions = quiz.questions;
const handleAnswerOptionClick = (isCorrect) => {
if (isCorrect) {
setScore(score + 1);
}
const nextQuestion = currentQuestion + 1;
if (nextQuestion < quizQuestions.length) {
setCurrentQuestion(nextQuestion);
} else {
setShowScore(true);
}
};
quizQuestions.map((quizQuestions)=> {
return (
<div className='questions'>
<div className="questions_row">
{showScore ? (
<div className='score-section'>
You scored {score} out of {quizQuestions.length}
</div>
) : (
<>
<QuestionsProduct
title="Introduction to Programming2"
questioNum={currentQuestion + 1}
question={quizQuestions[currentQuestion].quizQuestions.questionText}
answers={quizQuestions[currentQuestion].quizQuestions.answerOptions.map((answerOption) => (
<label onClick={() => handleAnswerOptionClick(quizQuestions.answerOption.isCorrect)}
type="checkbox">{answerOption.quizQuestions.answerText}</label>
))}
/>
</>
)}
</div>
</div>);
})
}
json 文件名为 quiz.json。我目前在内部拥有这些数据,但是我想创建更多问题,因此 json 文件将是理想的。这是创建的json文件
[{ "questions" : {
"questionText": "What is the capital of France?",
"answerOptions": [
{ "answerText": "New York", "isCorrect": false },
{ "answerText": "London", "isCorrect": false },
{ "answerText": "Paris", "isCorrect": true },
{ "answerText": "Dublin", "isCorrect": false }
]
},
"questionText2": "What is the capital of France 2?",
"answerOptions": [
{ "answerText": "New York", "isCorrect": false },
{ "answerText": "London", "isCorrect": false },
{ "answerText": "Paris", "isCorrect": true },
{ "answerText": "Dublin", "isCorrect": false }
]
}
]
【问题讨论】:
-
quizQuestions 有要映射的数据吗?请添加更多代码以及从哪里获取问题数据
-
是的,它从 jason 文件中读取。这是整个代码:
标签: reactjs dictionary undefined