在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/HTML/ 關于react中setState的問題,今天無意中發(fā)現(xiàn)的,請各位朋友幫忙看一下

關于react中setState的問題,今天無意中發(fā)現(xiàn)的,請各位朋友幫忙看一下 小的實在看不明白

首先 下面是我的第一段代碼:

let testValue = this.state.testValue;
    this.setState({testValue: testValue + 1});
    console.log(this.state.testValue);
    this.setState({testValue: testValue + 1});
    console.log(this.state.testValue);
    setTimeout(() => {
      // 注意下面的testValue的下段代碼的變化
      this.setState({testValue:testValue + 1});
      console.log(this.state.testValue);
      this.setState({testValue:testValue + 1});
      console.log(this.state.testValue);
    }, 0);

頁面上console中的輸出結(jié)果是:

clipboard.png

接著是另外一段代碼:
let testValue = this.state.testValue;

this.setState({testValue: testValue + 1});
console.log(this.state.testValue);
this.setState({testValue: testValue + 1});
console.log(this.state.testValue);
setTimeout(() => {
// testValue這里是兩段代碼的不同點
  this.setState({testValue:this.state.testValue + 1});
  console.log(this.state.testValue);
  this.setState({testValue:this.state.testValue + 1});
  console.log(this.state.testValue);
}, 0);

clipboard.png

請問為什么呢?ps:最開始的時候testValue默認值為1,請各位不吝賜教!

回答
編輯回答
離人歸

https://reactjs.org/docs/reac...
setState() enqueues changes to the component state and tells React that this component and its children need to be re-rendered with the updated state. This is the primary method you use to update the user interface in response to event handlers and server responses.
以上是官方文檔對批量setState的解釋,只說了說setState會排隊,但實際上,在當前版本中(16),在不同的地方批量執(zhí)行setState會有不同的表現(xiàn)。

以下是官方文檔中給的一個STO鏈接,說明在什么時候setState會被批量處理
In depth: When and why are setState() calls batched?(深入了解:什么時候并且為什么setState()調(diào)用會被合并)

Currently (React 16 and earlier), only updates inside React event handlers are batched by default. There is an unstable API to force batching outside of event handlers for rare cases when you need it.

In future versions (probably React 17 and later), React will batch all updates by default so you won't have to think about this. As always, we will announce any changes about this on the React blog and in the release notes.
現(xiàn)在(React 16 和之前),在默認情況下,只有直接在React event handlers里寫的setState會被合并處理
未來版本(大概從React 17 開始),React會默認合并所有的setState

下面官方文檔中給的另一個鏈接
In depth: Why isn’t this.state updated immediately?(深入了解:為什么this.state沒有被立刻更新?)

2017年7月5日 19:00
編輯回答
嫑吢丕

let testValue = this.state.testValue; // testValue 就是1了, 不是響應式的哈

2017年4月12日 13:44
編輯回答
傲嬌范

想明白了,因為在setTimeout里面的testValue !== this.state.testValue的,這樣便能說的通了

2018年7月4日 07:41