我正在使用firebase为我的作业制作一个简单的测验应用程序。当我从firebase检索我的问题时,我得到一个包含1个对象的数组,其中包含2个自己的对象。
如下所示:

我想把它们分别呈现在虚拟dom上,就像测验一样。有没有一种方法可以像使用Questions.Q1.Question一样遍历它们,但当用户按下next按钮时,它会动态地切换到Questions.Q2.Question来回答所有问题。
我收到了这样的问题:
getQuestions() {
const firebaseRef = firebase.database().ref("Quizes").child("JavaScript").child("Quiz 2").child("Questions");
firebaseRef.on("value", snap => {
this.setState(prevState => ({
Questions: [...prevState.Questions, snap.val()]
}))
})
}然后渲染它们:
renderQuiz() {
const { Questions, currentQuestion } = this.state;
let QTile, choice_1, choice_2, choice_3, choice_4 = "";
Questions.map(value => {
QTile = value.Q1.Question;
choice_1 = value.Q1.Choice_1;
choice_2 = value.Q1.Choice_2;
choice_3 = value.Q1.Choice_3;
choice_4 = value.Q1.Choice_4;
})
return (
<div className="panel-group questions">
<div className="panel panel-primary">
<div className="panel-heading">{QTile}</div>
<div className="panel-body">
<input type="radio" value={choice_1} /> {choice_1}
</div>
<div className="panel-body">
<input type="radio" value={choice_2} /> {choice_2}
</div>
<div className="panel-body">
<input type="radio" value={choice_3} /> {choice_3}
</div>
<div className="panel-body">
<input type="radio" value={choice_4} /> {choice_4}
</div>
</div>
<button className="btn btn-info" onClick={this.nextQuestion} style={{ float: "right", marginTop: "15px" }}>Next</button>
</div>
)
}下一个问题当前为空:
nextQuestion() {
console.log("Next Question");
}发布于 2018-09-17 01:50:40
第一个解决方案:
在检索问题对象时,您可以使用Object.keys。这会产生一个包含对象键的数组。您可以将它们存储在字段或状态中,以及引用此数组中当前位置的索引中。
所以(很抱歉,我从来没有用过Firebase,我会检查我是否可以让它适应你的代码),你的最终状态将是:
{
questions: { /* Object of questions, with keys Q1, Q2 and so */ },
currentQuestionIndex: /* some integer that you would increment */
}然后,要访问您的问题,您需要(在您的render方法中):
const { questions, currentQuestionIndex } = this.state;
const currentQuestionKey = Object.keys(questions)[currentQuestionIndex];
const currentQuestion = questions[currentQuestionKey];并更新问题(在您的nextQuestion中):
this.setState({ ...this.state, currentQuestionIndex: currentQuestionIndex + 1});更好的解决方案:
另一种选择是直接使用Object.values函数将Questions转换为数组。
https://stackoverflow.com/questions/52356720
复制相似问题