由于setState是异步的,是不是通过回调队列执行的?

我是 React 的新手,正在学习 setState 在幕后是如何工作的。因此,我想就此提出一些问题。首先,setState 总是异步的吗?如果不是在什么一般情况下它是同步的。其次,setState 中的异步是如何通过 web api 执行的,然后是回调队列?伙计们,如果有什么不清楚的,请告诉我。我只是真的需要你的帮助。


慕尼黑的夜晚无繁华
浏览 161回答 3
3回答

红颜莎娜

是的。它总是异步的,从不同步。开发人员的常见错误是这样的 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   } }而且您无法确定状态更新需要多长时间。

长风秋雁

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 {&nbsp; state = {&nbsp; &nbsp; counter: 0&nbsp; };&nbsp; componentDidMount() {&nbsp; &nbsp; // const intervalId = setInterval(this.updateState, 5000);&nbsp; &nbsp; // this.setState({intervalId: intervalId});&nbsp; &nbsp; this.counter.addEventListener("mousedown", this.updateState);&nbsp; }&nbsp; componentWillUnmount() {&nbsp; &nbsp; this.counter.removeEventListener("mousedown", this.updateState);&nbsp; &nbsp; // clearInterval(this.state.intervalId);&nbsp; }&nbsp; updateState = event => {&nbsp; &nbsp; console.log("= = = = = = = = = = = =");&nbsp; &nbsp; console.log("EVENT:", event ? event.type : "timer");&nbsp; &nbsp; console.log("Pre-setState:", this.state.counter);&nbsp; &nbsp; this.setState({&nbsp; &nbsp; &nbsp; counter: this.state.counter + 1&nbsp; &nbsp; });&nbsp; &nbsp; console.log("Post-setState:", this.state.counter);&nbsp; };&nbsp; render() {&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; <div className="App">&nbsp; &nbsp; &nbsp; &nbsp; <span onClick={this.updateState} ref={elem => (this.counter = elem)}>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Counter at {this.state.counter}&nbsp; &nbsp; &nbsp; &nbsp; </span>&nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; );&nbsp; }}const rootElement = document.getElementById("root");ReactDOM.render(<App />, rootElement);控制台日志&nbsp; &nbsp; = = = = = = = = = = = =&nbsp; &nbsp; EVENT: mousedown&nbsp;&nbsp; &nbsp; Pre-setState:&nbsp;&nbsp; &nbsp; 0&nbsp; &nbsp; Post-setState:&nbsp;&nbsp; &nbsp; 1&nbsp; &nbsp; = = = = = = = = = = = =&nbsp;&nbsp; &nbsp; EVENT: click&nbsp;&nbsp; &nbsp; Pre-setState:&nbsp;&nbsp; &nbsp; 1&nbsp; &nbsp; Post-setState:&nbsp;&nbsp; &nbsp; 1正如您在控制台日志中看到的那样,mousedown事件状态更改会立即反映出来,但onClick更改是异步的,或者更好地说是批处理。所以最好我们假设状态更改将是异步的,并使用回调处理程序来避免错误。当然,回调中的任何内容都将通过 javascript 中的事件循环。希望有帮助!!!
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript