点击名为gameIp函数的按钮后,我从数据库中下载了一组问题和答案,例如
state = {
qBank: {
Correct: "Tomek"
Question 1: "What is your name?"
RouteId: 1
Answers: ["ala", "ola", "Tomek", "jan"]
}
}
为“ if(id(id === point.RouteId))”分配一个名称 问题是Uncaught TypeError版本中弹出的错误:无法读取未定义的“ map”属性。我不能解决这个问题。要求有经验的程序员偷看我在哪里犯错了?
gameIp(id) {
const newQuestion2 = []
for (const point of this.state.qBank) {
if (id === point.RouteId) {
newQuestion2.push({
question: point.Question1,
answers: [...point.Answers],
correct: point.Correct,
id: point.Id
});
}
}
this.setState({ qBank: newQuestion2 })
}
在render方法中,我显示为:
{this.state.qBank.map(({ question, answers, correct, id }) => (
<QuestionBox key={id} question={question} options={answers} selected={answer => this.computeAnswer(answer, correct)} />
)
)}
QuestionBox看起来像这样:
import React, { useState } from 'react';
const QuestionBox = ({ question, options, selected }) => {
const [answers, setAnswer] = useState(options);
return (
<div className="questionBox">
<div className="question">{question}</div>
{answers.map((text, id) => (
<button key={id} className="answerBtn" onClick={() => {
setAnswer([text]);
selected(text)
}}>{text}</button>
))}
</div>
)
}
export default QuestionBox;