我想创建一个重置按钮,在测验结束时重置测验游戏。
我创建了一个按钮和一个应该处理事件的函数。但是当默认值被重新初始化时,问题不会显示在屏幕上。
constructor(props) {
super(props);
this.state = {
Replay: false,
counter: 0,
questionId: 1,
question: '',
answerOptions: [],
answer: '',
answersCount: {
Clever: 0,
Just_average: 0,
Very_dull: 0
},
result: ''
};
this.handleAnswerSelected = this.handleAnswerSelected.bind(this);
}
componentWillMount() {
const shuffledAnswerOptions = quizQuestions.map((question) => this.shuffleArray(question.answers));
this.setState({
question: quizQuestions[0].question,
answerOptions: shuffledAnswerOptions[0]
});
}
...........................................................
// Even handler function
restart(event){
this.setState ({
counter: 0,
questionId: 1,
question: '',
answerOptions: [],
answer: '',
answersCount: {
Clever: 0,
Just_average: 0,
Very_dull: 0,
},
result: ''
})
}
放置在App.js的渲染/返回中的代码
</div>
{this.state.result ? this.renderResult() : this.renderQuiz()}
</div>
.......................
renderQuiz(){ 返回( ); }
renderResult(){ 返回( ); }
答案 0 :(得分:0)
当您在构造函数+ componentWillMount中设置相同的状态时,在重置时,您可以创建类似getNewState的函数,通过删除componentWillMount可以在两个地方重用。 如果开始时所有数据都可用,则可以使用此方法。
如果要从api获取一些数据,则必须将api数据与componentWillMount中的状态合并。但是,虽然已经可以进行数据重置,但是可以按原样使用getNewState。
如下所示。
constructor(props) {
super(props);
const state = this.getNewState();
this.state = state;
this.handleAnswerSelected = this.handleAnswerSelected.bind(this);
}
function getNewState() {
const shuffledAnswerOptions = quizQuestions.map((question) => this.shuffleArray(question.answers));
return {
Replay: false,
counter: 0,
questionId: 1,
question: quizQuestions[0].question,
answerOptions: shuffledAnswerOptions[0],
answer: '',
answersCount: {
Clever: 0,
Just_average: 0,
Very_dull: 0
},
result: ''
};
}
// Even handler function
restart(event){
const state = this.getNewState();
this.setState(state);
}