首頁 web前端 js教程 總結React中的setState

總結React中的setState

Dec 19, 2019 pm 05:10 PM
react setstate

總結React中的setState

react中setState方法到底是異步還是同步,其實這個是分在什麼條件下是異步或是同步。

1.先來回顧react元件中改變state的幾種方式:


import React, { Component } from 'react'class Index extends Component {
    state={
        count:1
    }
    test1 = () => {        // 通过回调函数的形式
        this.setState((state,props)=>({
            count:state.count+1
        }));
        console.log('test1 setState()之后',this.state.count);
    }
    test2 = () => {        // 通过对象的方式(注意:此方法多次设置会合并且只调用一次!)
        this.setState({
            count:this.state.count+1
        });
        console.log('test2 setState()之后',this.state.count);
    }
    test3 = () => {        // 不能直接修改state的值,此方法强烈不建议!!!因为不会触发重新render
        this.state.count += 1;
    }
    test4 = () => {        // 在第二个callback拿到更新后的state
        this.setState({
            count:this.state.count+1
        },()=>{// 在状态更新且页面更新(render)后执行
            console.log('test4 setState()之后',this.state.count);
        });
    }
    render() {
        console.log('render');        
        return (            
        <p>
                <h1>currentState:{this.state.count}</h1>
                <button onClick={this.test1}>测试1</button>
                <button onClick={this.test2}>测试2</button>
                <button onClick={this.test3} style={{color:&#39;red&#39;}}>测试3</button>
                <button onClick={this.test4}>测试4</button>
            </p>        )
    }
}
export default Index;
登入後複製

#2.setState ()更新狀態是非同步還是同步:

需要判斷執行setState的位置

同步:在react控制的回呼函數中:生命週期鉤子/react事件監聽回調


import React, { Component } from &#39;react&#39;class Index extends Component {
    state={
        count:1
    }    /* 
    react事件监听回调中,setState()是异步状态    */
    update1 = () => {
        console.log(&#39;update1 setState()之前&#39;,this.state.count);        
        this.setState((state,props)=>({
            count:state.count+1
        }));
        console.log(&#39;update1 setState()之后&#39;,this.state.count);
    }    /* 
    react生命周期钩子中,setState()是异步更新状态    */
    componentDidMount() {
        console.log(&#39;componentDidMount setState()之前&#39;,this.state.count);        
        this.setState((state,props)=>({
            count:state.count+1
        }));
        console.log(&#39;componentDidMount setState()之后&#39;,this.state.count);
    }
    
    render() {
        console.log(&#39;render&#39;);        
        return (            
        <p>
                <h1>currentState:{this.state.count}</h1>
                <button onClick={this.update1}>测试1</button>
                <button onClick={this.update2}>测试2</button>
            </p>        )
    }
}
export default Index;
登入後複製

非同步:非react控制的非同步回呼函數中:定時器回呼/原生事件監聽回呼/Promise


import React, { Component } from &#39;react&#39;class Index extends Component {
    state={
        count:1
    }    /* 
    定时器回调    */
    update1 = () => {
        setTimeout(()=>{
            console.log(&#39;setTimeout setState()之前&#39;,this.state.count);//1
            this.setState((state,props)=>({
                count:state.count+1
            }));
            console.log(&#39;setTimeout setState()之后&#39;,this.state.count);//2        
            });
    }    /* 
    原生事件回调    */
    update2 = () => {
        const h1 = this.refs.count;
        h1.onclick = () => {
            console.log(&#39;onClick setState()之前&#39;,this.state.count);//1
            this.setState((state,props)=>({
                count:state.count+1
            }));
            console.log(&#39;onClick setState()之后&#39;,this.state.count);//2        
            }
    }    /* 
    Promise回调    */
    update3 = () => {
        Promise.resolve().then(value=>{
            console.log(&#39;Promise setState()之前&#39;,this.state.count);//1
            this.setState((state,props)=>({
                count:state.count+1
            }));
            console.log(&#39;Promise setState()之后&#39;,this.state.count);//2        
            });
    }
    
    render() {
        console.log(&#39;render&#39;);        return (            
        <p>
                <h1 ref=&#39;count&#39;>currentState:{this.state.count}</h1>
                <button onClick={this.update1}>测试1</button>
                <button onClick={this.update2}>测试2</button>
                <button onClick={this.update3}>测试3</button>
            </p>        )
    }
}
export default Index;
登入後複製

3.setState()多次呼叫的問題:

## 異步的setState()

(1)多次調用,處理方法:

setState({}):合併更新一次狀態,只調用一次render()更新介面,多次調用會合併為一個,後面的值會覆蓋前面的值。

setState(fn):更新多次狀態,只呼叫一次render()更新介面,多次呼叫

不會合併為一個,後面的值會覆寫前面的值。


import React, { Component } from &#39;react&#39;class Index extends Component {
    state={
        count:1
    }
    update1 = () => {
        console.log(&#39;update1 setState()之前&#39;,this.state.count);        
        this.setState((state,props)=>({
            count:state.count+1
        }));
        console.log(&#39;update1 setState()之后&#39;,this.state.count);
        console.log(&#39;update1 setState()之前2&#39;,this.state.count);        
        this.setState((state,props)=>({
            count:state.count+1
        }));
        console.log(&#39;update1 setState()之后2&#39;,this.state.count);
    }
    update2 = () => {
        console.log(&#39;update2 setState()之前&#39;,this.state.count);        
        this.setState({
            count:this.state.count+1
        });
        console.log(&#39;update2 setState()之后&#39;,this.state.count);
        console.log(&#39;update2 setState()之前2&#39;,this.state.count);        
        this.setState({
            count:this.state.count+1
        });
        console.log(&#39;update2 setState()之后2&#39;,this.state.count);
    }
    update3 = () => {
        console.log(&#39;update3 setState()之前&#39;,this.state.count);        
        this.setState({
            count:this.state.count+1
        });
        console.log(&#39;update3 setState()之后&#39;,this.state.count);
        console.log(&#39;update3 setState()之前2&#39;,this.state.count);        
        this.setState((state,props)=>({
            count:state.count+1
        }));// 这里需要注意setState传参为函数模式时,state会确保拿到的是最新的值
        console.log(&#39;update3 setState()之后2&#39;,this.state.count);
    }
    update4 = () => {
        console.log(&#39;update4 setState()之前&#39;,this.state.count);        
        this.setState((state,props)=>({
            count:state.count+1
        }));
        console.log(&#39;update4 setState()之后&#39;,this.state.count);
        console.log(&#39;update4 setState()之前2&#39;,this.state.count);        
        this.setState({
            count:this.state.count+1
        });// 这里需要注意的是如果setState传参为对象且在最后,那么会与之前的setState合并
        console.log(&#39;update4 setState()之后2&#39;,this.state.count);
    }
    render() {
        console.log(&#39;render&#39;);        return (            
        <p>
                <h1>currentState:{this.state.count}</h1>
                <button onClick={this.update1}>测试1</button>
                <button onClick={this.update2}>测试2</button>
                <button onClick={this.update3}>测试3</button>
                <button onClick={this.update4}>测试4</button>
            </p>        )
    }
}
export default Index;
登入後複製

(2)如何得到setState非同步更新後的狀態資料:

在setState()的callback回呼函數中

# 4.react中常見的setState面試題(setState執行順序)


import React, { Component } from &#39;react&#39;// setState执行顺序class Index extends Component {
    state={
        count:0
    }
    componentDidMount() {        this.setState({count:this.state.count+1});        
    this.setState({count:this.state.count+1});
        console.log(this.state.count);// 2 => 0
        this.setState(state=>({count:state.count+1}));        
        this.setState(state=>({count:state.count+1}));
        console.log(this.state.count);// 3 => 0
        setTimeout(() => {            
        this.setState({count:this.state.count+1});
            console.log(&#39;setTimeout&#39;,this.state.count);// 10 => 6
            this.setState({count:this.state.count+1});
            console.log(&#39;setTimeout&#39;,this.state.count);// 12 => 7        
            });
        Promise.resolve().then(value=>{            
        this.setState({count:this.state.count+1});
            console.log(&#39;Promise&#39;,this.state.count);// 6 => 4
            this.setState({count:this.state.count+1});
            console.log(&#39;Promise&#39;,this.state.count);// 8 => 5        
            });
    }
    render() {
        console.log(&#39;render&#39;,this.state.count);// 1 => 0  // 4 => 3 // 5 => 4 // 7 => 5 // 9 => 6 // 11 => 7
        return (            <p>
                <h1>currentState:{this.state.count}</h1>
                <button onClick={this.update1}>测试1</button>
                <button onClick={this.update2}>测试2</button>
                <button onClick={this.update3}>测试3</button>
                <button onClick={this.update4}>测试4</button>
            </p>        )
    }
}
export default Index;
登入後複製

總結:react中setState()更新狀態的2種寫法

1)setState(updater,[callback])

updater:為傳回stateChange物件的函數:(state,props)=>stateChange,收到的

state和props都保證為最新

2)setState(stateChange,[callback])

stateChange為對象,callback是可選的回呼函數,在

狀態更新且介面更新後面才執行

注意:

物件是函數方式的簡寫方式

如果新狀態不依賴原始狀態,則使用物件方式;

如果新狀態依賴原始狀態,則使用函數方式;

如果需要在setState()後取得最新的狀態數據,在第二個callback函數中取得

本文來自

js教學 欄目,歡迎學習!  

以上是總結React中的setState的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

<🎜>:泡泡膠模擬器無窮大 - 如何獲取和使用皇家鑰匙
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
北端:融合系統,解釋
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
Mandragora:巫婆樹的耳語 - 如何解鎖抓鉤
3 週前 By 尊渡假赌尊渡假赌尊渡假赌

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

Java教學
1664
14
CakePHP 教程
1423
52
Laravel 教程
1321
25
PHP教程
1269
29
C# 教程
1249
24
如何利用React和RabbitMQ建立可靠的訊息應用 如何利用React和RabbitMQ建立可靠的訊息應用 Sep 28, 2023 pm 08:24 PM

如何利用React和RabbitMQ建立可靠的訊息傳遞應用程式引言:現代化的應用程式需要支援可靠的訊息傳遞,以實現即時更新和資料同步等功能。 React是一種流行的JavaScript庫,用於建立使用者介面,而RabbitMQ是一種可靠的訊息傳遞中間件。本文將介紹如何結合React和RabbitMQ建立可靠的訊息傳遞應用,並提供具體的程式碼範例。 RabbitMQ概述:

React Router使用指南:如何實現前端路由控制 React Router使用指南:如何實現前端路由控制 Sep 29, 2023 pm 05:45 PM

ReactRouter使用指南:如何實現前端路由控制隨著單頁應用的流行,前端路由成為了一個不可忽視的重要部分。 ReactRouter作為React生態系統中最受歡迎的路由庫,提供了豐富的功能和易用的API,使得前端路由的實作變得非常簡單和靈活。本文將介紹ReactRouter的使用方法,並提供一些具體的程式碼範例。安裝ReactRouter首先,我們需要

PHP、Vue和React:如何選擇最適合的前端框架? PHP、Vue和React:如何選擇最適合的前端框架? Mar 15, 2024 pm 05:48 PM

PHP、Vue和React:如何選擇最適合的前端框架?隨著互聯網技術的不斷發展,前端框架在Web開發中起著至關重要的作用。 PHP、Vue和React作為三種代表性的前端框架,每一種都具有其獨特的特徵和優勢。在選擇使用哪種前端框架時,開發人員需要根據專案需求、團隊技能和個人偏好做出明智的決策。本文將透過比較PHP、Vue和React這三種前端框架的特徵和使

Java框架與前端React框架的整合 Java框架與前端React框架的整合 Jun 01, 2024 pm 03:16 PM

Java框架與React框架的整合:步驟:設定後端Java框架。建立專案結構。配置建置工具。建立React應用程式。編寫RESTAPI端點。配置通訊機制。實戰案例(SpringBoot+React):Java程式碼:定義RESTfulAPI控制器。 React程式碼:取得並顯示API回傳的資料。

如何利用React開發一個響應式的後台管理系統 如何利用React開發一個響應式的後台管理系統 Sep 28, 2023 pm 04:55 PM

如何利用React開發一個響應式的後台管理系統隨著互聯網的快速發展,越來越多的企業和組織需要一個高效、靈活、易於管理的後台管理系統來處理日常的操作事務。 React作為目前最受歡迎的JavaScript庫之一,提供了一種簡潔、高效和可維護的方式來建立使用者介面。本文將介紹如何利用React開發一個響應式的後台管理系統,並給出具體的程式碼範例。建立React專案首先

vue.js vs.反應:特定於項目的考慮因素 vue.js vs.反應:特定於項目的考慮因素 Apr 09, 2025 am 12:01 AM

Vue.js適合中小型項目和快速迭代,React適用於大型複雜應用。 1)Vue.js易於上手,適用於團隊經驗不足或項目規模較小的情況。 2)React的生態系統更豐富,適合有高性能需求和復雜功能需求的項目。

React在HTML中的作用:增強用戶體驗 React在HTML中的作用:增強用戶體驗 Apr 09, 2025 am 12:11 AM

React通過JSX與HTML結合,提升用戶體驗。 1)JSX嵌入HTML,使開發更直觀。 2)虛擬DOM機制優化性能,減少DOM操作。 3)組件化管理UI,提高可維護性。 4)狀態管理和事件處理增強交互性。

react有哪些閉包 react有哪些閉包 Oct 27, 2023 pm 03:11 PM

react有事件處理函數、useEffect和useCallback、高階元件等等閉包。詳細介紹:1、事件處理函數閉包:在React中,當我們在元件中定義事件處理函數時,函數會形成一個閉包,可以存取元件作用域內的狀態和屬性。這樣可以在事件處理函數中使用元件的狀態和屬性,實現互動邏輯;2、useEffect和useCallback中的閉包等等。

See all articles