redux的簡單使用

2021-10-23 20:29:59 字數 2483 閱讀 9541

redux是乙個狀態管理工具,一般在多互動,多資料來源的時候使用redux編寫程式的時候方便很多,**結構也更加清晰。

以下是廣為流傳的redux工作流程圖

以上的流程我個人理解是:

是乙個修改store資料的乙個流程圖,首先元件中的某個操作需要修改store的資料,然後就要通知store,元件就先將要修改的事情告訴action,通過store.dispatch(action)傳給store,store知道這件事之後,就將當前的資料和傳過來的action一併傳給reducers,reducers接收到這兩個引數,通過action的type屬性知道要對state做什麼修改,修改好之後,將最新的state傳給store,然後元件通過store.subscribe()監聽到資料發生了變化,就通過store.getstate()方法在賦值給元件的state,然後元件就能獲取到最新的state了。

在專案中建立並使用

1 :建立乙個store資料夾,然後建立乙個index.js,這個資料夾是用來建立唯一的store的,再建立乙個reducer.js檔案,將reducer引入index.js中

store->index.js

// 建立乙個store 

import

from

'redux'

import reducer from

'./reducer'

const store =

createstore

( reducer,

window.__redux_devtools_extension__ && window.

__redux_devtools_extension__()

)export

default store

store->reducer.js

注意:因為store的資料是不能修改的,所以在reducer中需要深拷貝乙份store資料,在進行修改,將修改好的資料return

// 這是action的type

import

from

'./actiontypes'

// state的資料

const de****tstate =

// reducer是乙個純函式,給定固定的輸入,就一定會有固定的輸出,而且不會有任何的***

export

default

(state=de****tstate,action)

=>

return state

}

store->actiontypes.js

export

const

cange_input_value

='chang_input_value'

2.建立好以上檔案就可以在元件中獲取store的資料了,使用store.getstate()獲取store的資料
constructor

(props)

// 使用

render()

>

)}

3.如果改變input的值的話,就需要建立乙個action,將改變的值傳給store,然後就是做index.js->reducer.js的內容
constructor

(props)

// 監聽onchange事件

input value=

onchange=

>

handelchangeinput

(e)

以上gethandelchangeinput方法是封裝的乙個action,單獨寫到乙個js檔案中

store->actioncreators.js

import

from

'./actiontypes'

export

const

gethandelchangeinput

=(value)

=>()

;

這時頁面上輸入值,store的值是變化的,但是頁面沒顯示出來,這時候怎麼做到讓輸入的值,頁面也馬上顯示對應的值呢,通過store.subscribe()訂閱store的改變,只要store發生改變自定義的函式就會呼叫一次

元件**:

constructor

(props)

// 監聽store的改變

handestorechange()

這樣子就是乙個redux的工作流

看一下store的目錄結構吧

最後store裡的幾個重要的api

簡單使用redux

import from redux 用於建立倉庫 import from redux const initialstate const add to cart add to cart const cartreducer function state initialstate,action break...

react中簡單使用redux

如果你一點不熟悉redux,看看這個 專案搭建好之後,安裝一下依賴,安裝一下redux 和 react redux 在src目錄下建乙個redux資料夾,在redux資料夾下建action資料夾和reducer資料夾,分別放我們的action和reducer 1,首先編寫我們的action。acti...

redux 的簡單實用案例

檔案目錄如下 整體 如下 這是 action 的建構函式 const sendaction module.exports conat rootreducer state,action 第乙個引數是預設狀態,我們可以定義乙個初始化的 state,然後進行賦值 const initstate const...