【发布时间】:2020-05-12 22:25:27
【问题描述】:
我创建了一个测验,并且我有一个组件可以在测验结束时向用户显示结果。我还想向用户展示他们对/错的问题。
目前我正在显示questions 和correctAnswer,但是所有正确答案都显示在每个问题下。
我想在每个问题下显示一个correctanswer。我尝试了许多解决方案,但无法使其正常工作。我认为我可以map 解决每个问题,然后在.map 内执行forEach 以返回每个问题的正确答案,但它不起作用。
这是我目前所拥有的:
resultsCard.js组件:
import React from "react";
import "./../assets/style.css";
const ResultCard = ({
score,
playAgain,
getQuestions,
questions,
userAnswer,
correctAnswer
}) => {
return (
<div>
<div>You scored {score} out of 5! </div>
<div className="playBtnBox">
<button className="playBtn" type="button" onClick={getQuestions}>
Play again
</button>
</div>
<div>
{questions.map(question => {
return (
<div>
<div className="questionBox"> {question}</div>
<div className="questionBox"> {correctAnswer}</div>
</div>
);
})}
</div>
</div>
);
};
export default ResultCard;
index.js 正在使用的结果:
class QuizBee extends Component {
state = {
qBank: [],
score: 0,
responses: 0
};
getQuestions = () => {
quizService().then(question => {
this.setState({
qBank: question,
score: 0,
responses: 0
});
});
};
componentDidMount() {
this.getQuestions();
}
render() {
return (
<div className="container">
<div className="title">Quiz Me</div>
{this.state.qBank.length > 0 &&
this.state.responses < 5 &&
this.state.qBank.map(quest => {
const { question, answers, correct, questionId } = quest;
return (
<QuestionBox
question={question}
options={answers}
key={questionId}
correct={correct}
incrementScore={this.incrementScore}
incrementResponse={this.incrementResponse}
/>
);
})}
{this.state.responses === 5 && (
<h2>
<ResultCard
score={this.state.score}
getQuestions={this.getQuestions}
questions={this.state.qBank.map(quest => {
const {question} = quest;
return (
question
)
})}
correctAnswer={this.state.qBank.map(quest => {
const {correct} = quest;
return (
correct
)
})}
/>
</h2>
)}
</div>
);
}
}
qBank 数据:
const qBank = [
{
question:
"Virgin Trains, Virgin Atlantic and Virgin Racing, are all companies owned by which famous entrepreneur? ",
answers: ["Richard Branson", "Alan Sugar", "Donald Trump", "Bill Gates"],
correct: "Richard Branson",
questionId: "099099"
},
{
question:
'Where is the train station "Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch"?',
answers: ["Wales", "Moldova", "Czech Republic", "Denmark"],
correct: "Wales",
questionId: "183452"
},
{
question:
"Which company did Valve cooperate with in the creation of the Vive?",
answers: ["HTC", "Oculus", "Google", "Razer"],
correct: "HTC",
questionId: "267908"
},
{
question: "What's the name of Batman's parents?",
answers: [
"Thomas & Martha",
"Joey & Jackie",
"Jason & Sarah",
"TodWhat is the most common surd & Mira"
],
correct: "Thomas & Martha",
questionId: "333247"
}
]
【问题讨论】:
-
你的代码没有按照你说的做,也就是说,据我所知,你不要在代码中使用 forEach
标签: javascript reactjs foreach