我正在尝试创建一个新的随机数,将其设置为方法后的状态。它在刷新时效果很好,但是单击按钮后无法“生成”新数字。
这是我目前的代码:
var QuizContainer = React.createClass({
randomNumber: function(){
return Math.floor((Math.random() * Data.length) + 0);
},
getInitialState: function(){
var rand = this.randomNumber();
return {
answerList: Data[rand].answer,
answerQuestion: Data[rand].question,
correctAnswer: Data[rand].correct,
score: 0,
timer: 30
}
},
success: function(){
this.setState({score: this.state.score + 1})
},
fail: function(){
this.setState({score: 0})
this.getInitialState();
},
handleClick: function(child){
child.props.singleAnswer == this.state.correctAnswer ? this.success() : this.fail()
},
render: function(){
return(
<div>
<Timer timer={this.state.timer} />
<Score currentScore={this.state.score} />
<QuestionContainer answerQuestion={this.state.answerQuestion} />
<ButtonContainer onClick={this.handleClick} correctAnswer={this.state.correctAnswer} answerList={this.state.answerList} />
</div>
)
}
})
module.exports = QuizContainer;
如果有人能够提供帮助,我将非常感激!谢谢!
最佳答案
getInitialState
返回一个对象。您只是调用this.getInitialState()
并丢弃该对象。要更新状态,您需要致电this.setState
fail: function(){
this.setState(this.getInitialState());
},
getInitialState周围没有魔术包装,该函数只是按照您的指示进行操作,实例化组件时,它由react使用。
我删除了
this.setState({score: 0})
,因为它是由您的getInitialState提供的。同样,ButtonContainer应该向上传递答案,而不是更新其道具并将其自身传递给onClick回调。如果您正在阅读的道具不是自己的,那是错误的。