3 回答
TA贡献1842条经验 获得超12个赞
是的。它总是异步的,从不同步。开发人员的常见错误是这样的
handleEvent(newValue) {
this.setState({ value: newValue }, () => {
// you can get the updated state here
console.log(this.state.value)
})
this.doSomething(newValue)
}
doSomething(newValue) {
// this.state.value is still the old value
if (this.state.value === newValue) {
// blabla
}
}
而且您无法确定状态更新需要多长时间。
TA贡献1757条经验 获得超7个赞
React setState 并不总是异步的,它取决于触发状态更改的方式。
1) 同步 - 如果操作在 Reactjs 世界之外,或者状态更改是由计时器或用户引发的 事件处理程序触发的,则 reactjs 无法批量更新并且必须立即改变状态。
2) 异步 如果状态改变是由 onClick 触发的,那么 Reactjs 可以批量更新状态以获得性能提升。
工作代码和框链接
和
参考帖子
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
class App extends React.Component {
state = {
counter: 0
};
componentDidMount() {
// const intervalId = setInterval(this.updateState, 5000);
// this.setState({intervalId: intervalId});
this.counter.addEventListener("mousedown", this.updateState);
}
componentWillUnmount() {
this.counter.removeEventListener("mousedown", this.updateState);
// clearInterval(this.state.intervalId);
}
updateState = event => {
console.log("= = = = = = = = = = = =");
console.log("EVENT:", event ? event.type : "timer");
console.log("Pre-setState:", this.state.counter);
this.setState({
counter: this.state.counter + 1
});
console.log("Post-setState:", this.state.counter);
};
render() {
return (
<div className="App">
<span onClick={this.updateState} ref={elem => (this.counter = elem)}>
Counter at {this.state.counter}
</span>
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
控制台日志
= = = = = = = = = = = =
EVENT: mousedown
Pre-setState:
0
Post-setState:
1
= = = = = = = = = = = =
EVENT: click
Pre-setState:
1
Post-setState:
1
正如您在控制台日志中看到的那样,mousedown事件状态更改会立即反映出来,但onClick更改是异步的,或者更好地说是批处理。
所以最好我们假设状态更改将是异步的,并使用回调处理程序来避免错误。当然,回调中的任何内容都将通过 javascript 中的事件循环。
希望有帮助!!!
添加回答
举报