存储在道具中的值 1 和 2 和 3 的值是 Math.floor(Math.random() * 100) 所以我想知道什么时候我 setState 和 numQuestions 的值, numCorrect 改变和渲染方法是因为我知道为什么这个渲染没有使三个值 1,2,3 再次被复制并且它们的值随着两个按钮的每次单击而改变。
class App extends Component {
constructor(props) {
super(props)
this.proposedAnswer = Math.floor(Math.random() * 3) + this.props.value1 + this.props.value2 + this.props.value3;
this.state = {
numQuestions : 0,
numCorrect : 0,
}
}
rightanswer= ()=> {
if(this.proposedAnswer === this.props.value1 + this.props.value2 + this.props.value3){
this.setState((oldstate)=> ({
numCorrect : oldstate.numCorrect +=1 ,
numQuestions : oldstate.numQuestions += 1 ,
}))
}else{
this.setState((oldstate)=> ({
numQuestions : oldstate.numQuestions += 1 ,
}))
}
}
falseanswer= ()=> {
if(this.proposedAnswer !== this.props.value1 + this.props.value2 + this.props.value3){
this.setState((oldstate)=> ({
numCorrect : oldstate.numCorrect +=1 ,
numQuestions : oldstate.numQuestions += 1 ,
}))
}else{
this.setState((oldstate)=> ({
numQuestions : oldstate.numQuestions += 1 ,
}))
}
}
render() {
return (
<div className="App">
<div className="game">
<h2>Mental Math</h2>
<div className="equation">
<p className="text">{`${this.props.value1} + ${this.props.value2} +
${this.props.value3} = ${this.proposedAnswer}`}</p>
</div>
<button onClick={() => this.rightanswer()}>True</button>
<button onClick={() => this.falseanswer()}>False</button>
<p className="text">
Your Score: {this.state.numCorrect}/{this.state.numQuestions}
</p>
</div>
</div>
);
}
}
export default App;
当状态改变时,你的组件会重新渲染。但是,您的 props 不会改变,因为您没有从父组件传入新的 props,所以value1
, value2
, 并value3
保持不变。
如果您希望value
s 在状态更改时更改,一种方法是将所有value
s 移动到状态,在组件安装时初始化它们,并在组件更新时更新它们:
constructor(props) {
super(props);
this.state = {
numQuestions: 0,
numCorrect: 0
};
}
componentDidMount() {
this.generateValues();
}
componentDidUpdate(prevProps, prevState) {
if (this.state.numQuestions !== prevState.numQuestions) {
this.generateValues();
}
}
generateValues = () => {
const values = [...Array(3)].map(() => Math.floor(Math.random() * 100));
const correctAnswer = values.reduce((a, b) => a + b, 0);
const proposedAnswer = Math.floor(Math.random() * 3) + correctAnswer;
this.setState({
value1: values[0],
value2: values[1],
value3: values[2],
correctAnswer: correctAnswer,
proposedAnswer: proposedAnswer
});
};
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句