我编写了以下 react 组件来处理我使用 react 制作的扫雷克隆的难度级别。
我使用单选按钮作为难度输入,并希望根据所做的选择设置组件的状态。
我的问题是,每次我更改选择时,状态都会更新为我之前的选择,而不是当前选择的值。例如,在页面加载期间,选择的难度是“简单”。当我将难度更改为“困难”时,状态仍然显示初始设置,即“简单”(我做了一个状态的控制台日志来验证这一点)。
请帮忙。
import React, {Component} from 'react';
class Difficulty extends Component{
state = {
height: 8,
width: 8,
mines: 10,
};
setDifficulty(event){
let selectedDifficulty = event.target.value;
if (selectedDifficulty === "Easy") {
this.setState({
height: 8,
width: 8,
mines: 10,
});
}
if (selectedDifficulty === "Medium") {
this.setState({
height: 12,
width: 12,
mines: 20,
});
}
if (selectedDifficulty === "Hard") {
this.setState({
height: 16,
width: 16,
mines: 40,
});
}
this.props.updateDifficulty(this.state);
}
render(){
return(
<div className="game-difficulty">
<div className="difficulty" onChange={this.setDifficulty.bind(this)}>
<input type="radio" value="Easy" name="gender" defaultChecked="true" /> Easy
<input type="radio" value="Medium" name="gender" /> Medium
<input type="radio" value="Hard" name="gender" /> Hard
</div>
</div>
);
}
}
export default Difficulty;
最佳答案
setState
是异步的,因此如果您尝试在调用 setState
后立即使用它,this.state
仍将包含之前的值。
您可以改为在作为 setState
的第二个参数给出的函数中执行依赖于 this.state
的逻辑,该函数将在状态更新时运行。
setDifficulty(event) {
let selectedDifficulty = event.target.value;
let values;
if (selectedDifficulty === "Easy") {
values = {
height: 8,
width: 8,
mines: 10
};
}
if (selectedDifficulty === "Medium") {
values = {
height: 12,
width: 12,
mines: 20
};
}
if (selectedDifficulty === "Hard") {
values = {
height: 16,
width: 16,
mines: 40
};
}
this.setState(values, () => {
this.props.updateDifficulty(this.state);
});
}
关于javascript - React setstate 采用以前的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53136385/