鍍金池/ 問答/HTML/ React setState 不符合直覺

React setState 不符合直覺

我們說setState是批量更新

但是下面代碼顯示的star是3

有誰知道為什么嗎?

import React, { Component } from 'react';

class App extends Component {
    constructor(props) {
        super(props);
        this.timer = null;
        this.state = { star: 0 };
    }
    
    componentDidMount() {
        this.timer = setTimeout(() => {
            this.setState({ num: this.state.star + 1 });
            this.setState({ num: this.state.star + 1 });
            this.setState({ num: this.state.star + 1 });
        }, 5000);
    }
    
    render() {
        return <div>{this.state.star}</div>;
    }
    
    componentWillUnmount() {
        clearTimeout(this.timer);
    }
}

export default App;
回答
編輯回答
囍槑

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.
以上是官方文檔對(duì)批量setState的解釋,只說了說setState會(huì)排隊(duì),但實(shí)際上,在當(dāng)前版本中,在不同的地方批量執(zhí)行setState會(huì)有不同的表現(xiàn)。

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

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 和之前),在默認(rèn)情況下,只有直接在react生命周期React event handlers里寫的setState會(huì)被合并處理
未來版本(大概從React 17 開始),React會(huì)默認(rèn)合并所有的setState

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

2017年1月21日 03:26
編輯回答
風(fēng)畔

setState本身是異步的,會(huì)積累到一定程度給你更新狀態(tài),并不是馬上set就會(huì)馬上change,內(nèi)部有做優(yōu)化的

2018年7月16日 11:58