这是我在组件中的代码。
this.state = {
strength: 0,
dexterity: 0,
intelligence: 0,
health: 0
};
this.increaseBasicAttrStrength = this.increaseBasicAttrStrength.bind(this);
this.updateApp = this.updateApp.bind(this);
}
increaseBasicAttrStrength(event) {
this.setState(prevState => ({
strength: prevState.strength + 10,
dexterity: prevState.dexterity,
intelligence: prevState.intelligence,
health: prevState.health
}));
this.updateApp();
}
updateApp() {
console.log(this.state);
this.props.basicAttrsHandler(this.state);
}
即使在updateBasicAttrStrength(...)之后调用了updateApp(...),当我控制状态时,它也会显示如下。
{strength: 0, dexterity: 0, intelligence: 0, health: 0}
状态尚未更新。
请帮我解决这个问题。
答案 0 :(得分:3)
不确定updateApp
在做什么,但是如果您在setState
调用完成后之后需要调用它,则应将其放在回调中。 SetState是异步的,因此不能保证在调用updateApp
之前发生了这些更新。使用回调可确保内部的任何代码在初始状态更新完成之前不会运行:
increaseBasicAttrStrength(event) {
this.setState(prevState => ({
strength: prevState.strength + 10,
dexterity: prevState.dexterity,
intelligence: prevState.intelligence,
health: prevState.health
}), () => this.updateApp())
}
答案 1 :(得分:1)
setState是异步的。您可以使用回调方法获取更新状态。
increaseBasicAttrStrength(event) {
this.setState(prevState => ({
strength: prevState.strength + 10,
dexterity: prevState.dexterity,
intelligence: prevState.intelligence,
health: prevState.health
}, () => {console.log(this.state)}));
}
答案 2 :(得分:1)
之所以如此,是因为假设setState
是异步的。参见this
答案 3 :(得分:1)
也许这项工作可以在回调状态更新后调用更新功能
increaseBasicAttrStrength(event) {
this.setState(prevState => ({
strength: prevState.strength + 10,
dexterity: prevState.dexterity,
intelligence: prevState.intelligence,
health: prevState.health
}),()=>{
this.updateApp(); //add this function in callback
});
}