我是ReactJS的初学者,刚开始学习并开始编写用于猜测数字的代码,但是猜测计数显示不同的值。 {this.state.attempts}
保留编号。用户尝试查找答案以显示正确值的尝试次数。但是{this.state.result}
会显示每次点击的结果,但是如果用户找到答案,它将显示以前的状态。我想知道这是怎么发生的。是因为它不在render()
下吗?
import React, { Component } from 'react';
export default class NoLifeCycComps extends Component {
constructor(props) {
super(props);
this.state = this.getInitialState();
this.checkValue = this.checkValue.bind(this);
this.updateInput = this.updateInput.bind(this);
}
randNum(){
return Math.floor((Math.random() * 100) + 1);
}
getInitialState(){
return {
num: this.randNum(),
inputValue: '',
attempts: 0,
result: '',
reset : false
}
}
reset() {
this.setState(this.getInitialState());
}
checkValue() {
this.setState((prevState) => {
return { attempts: prevState.attempts + 1 }
});
if (this.state.inputValue > this.state.num) {
this.state.result = "higher";
} else if (this.state.inputValue < this.state.num) {
this.state.result = "lesser";
} else if (this.state.inputValue == this.state.num) {
this.state.result = "you found it on " + this.state.attempts + "attempt(s)";
this.state.reset = true;
}
}
updateInput(e) {
this.setState({ inputValue: e.target.value })
}
render() {
return (
<div className = "numberGuess">
<h3> Guess the number </h3>
<input type = "text" value = { this.state.inputValue } onChange = { this.updateInput }/>
{this.state.reset ? <button onClick = { () => this.reset() }> start again! </button> : <button onClick = { () => this.checkValue() }> click </button>}
No.of Attempts took: { this.state.attempts } <br/>
<span> { this.state.result } </span>
</div>
);
}
}
答案 0 :(得分:5)
setState
是一个异步功能。 setState
的下一条语句可能没有更新的状态值。我也在您的代码中发现了突变状态更新。请避免突变更新。您应该使用setState
checkValue() {
let {
attempts,
inputValue,
num,
result,
reset
} = this.state;
attempts++;
if (inputValue > num) {
result = "higher";
} else if (inputValue < num) {
result = "lesser";
} else if (inputValue == num) {
result = "you found it on " + attempts + "attempt(s)";
reset = true;
}
this.setState({
attempts,
result,
reset
});
}
在此示例中,我们将现有状态值存储在变量中并对其进行操作。在计算结束时,我们只更新一次状态。