React redux的原理以及簡單使用

2021-09-02 23:36:59 字數 3105 閱讀 8029

當乙個react專案元件層級越來越深,頁面越來越多的時候,資料在各個元件層級和頁面之間傳遞的需求就會比較多,很多變數也需要做成可全域性管理的。在這個時候,redux和react-redux的使用就很有必要了。它們能幫助我們很方便的進行專案全域性性的資料管理。

下面,就寫一下我自己對reduxreact-redux的學習以及使用的心得,權當是對學習過程的一種記錄和分享。

action是把資料從應用(這裡之所以不叫 view 是因為這些資料有可能是伺服器響應,使用者輸入或其它非 view 的資料 )傳到 store 的有效載荷。它是 store 資料的唯一**。一般來說你會通過store.dispatch()將 action 傳到 store。

reducers指定了應用狀態的變化如何響應 actions併發送到 store 的,記住 actions 只是描述了有事情發生了這一事實,並沒有描述應用如何更新 state。

store就是把action和reducer聯絡到一起的物件,store本質上是乙個狀態樹,儲存了所有物件的狀態。任何ui元件都可以直接從store訪問特定物件的狀態。

redux中,所有的資料(比如state)被儲存在乙個store容器中 ,在乙個應用程式中只能有乙個store物件。當乙個store接收到乙個action,它將把這個action**給相關的reducer。reducer是乙個純函式,它可以檢視之前的狀態,執行乙個action並且返回乙個新的狀態。

provider其實就只是乙個外層容器,它的作用就是通過配合connect來達到跨層級傳遞資料。使用時只需將provider定義為整個專案最外層的元件,並設定好store。那麼整個專案都可以直接獲取這個store。它的原理其實是通過react中的context來實現的。它大致的核心**如下:

import react,  from 'react'

import from 'prop-types'

export default class provider extends component

}constructor()

}render()

}provider.childcontexttypes =

connect的作用是連線react元件與 redux store,它包在我們的容器元件的外一層,它接收上面 provider 提供的 store 裡面的 state 和 dispatch,傳給乙個建構函式,返回乙個物件,以屬性形式傳給我們的容器元件。

它共有四個引數mapstatetoprops, mapdispatchtoprops, mergeprops以及options。

mapstatetoprops的作用是將store裡的state(資料來源)繫結到指定元件的props中

mapdispatchtoprops的作用是將store裡的action(運算元據的方法)繫結到指定元件的props中

另外兩個方法一般情況下使用不到,這裡就不做介紹。。

那麼connect是怎麼將react元件與 redux store連線起來的呢?其主要邏輯可以總結成以下**:

import  from "react";

import react from "react";

import from 'prop-types'

class connect extends component

}componentwillmount() )

}componentwillunmount()

render() />}

}connect.contexttypes =

return connect

})export default connect

專案中關於redux的資料夾目錄如下

拿管理使用者資訊資料的需求來舉例

import  from "../constants/actiontypes";

import store from '../store/store'

export const switchuser = (data) => )}}

import  from "../constants/actiontypes";

const reduserinfo = (state = , action) =>

switch (action.type)

default:

return state}}

import  from 'redux'

import reducers from '../reducers/index'

let store = createstore(reducers)

export default store

//配置**,通過connect將元件和store連線起來

let mapstatetoprops = (state) => (

})let mapdispatchtoprops = (dispatch) => ({})

export default connect(mapstatetoprops, mapdispatchtoprops)(pageclass)

//通過props獲取使用者資訊

this.props.userinfo

import  from '../../redux/actions/userinfo'

switchuser()();

至此就完成了redux+react-redux的乙個簡單使用流

React redux的原理以及使用

當乙個react專案元件層級越來越深,頁面越來越多的時候,資料在各個元件層級和頁面之間傳遞的需求就會比較多,很多變數也需要做成可全域性管理的。在這個時候,redux和react redux的使用就很有必要了。它們能幫助我們很方便的進行專案全域性性的資料管理。下面,就寫一下我自己對redux和reac...

react redux的實現原理

react redux框架可以用來對react native進行資料流管理。redux是乙個用於ui布局框架的標準庫。redux的概念是通過ui binding來將redux和react繫結到一起,這樣可以避免ui 部分和store直接互動。從元件布局來講,當我們在構建乙個大型元件,且內部每個小模組...

react redux使用的方法

1.mapdispatchtoprops中使用bindactioncreators 2.import thunk from redux thunk 使用redux thunk中介軟體,我們可以在action構造器中返回乙個函式,而不是乙個物件。3.通常情況下,我們的專案可能會有龐大的資料,所以一般情...