长风秋雁
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 中的事件循环。希望有帮助!!!