Redux

Redux的設(shè)計(jì)思想:

Redux的工作流程:

首先,用戶發(fā)出Action

store.dispatch(action);

然后,Store自動(dòng)調(diào)用Reducer,并且傳入兩個(gè)參數(shù):當(dāng)前State和收到的Action。Reducer會(huì)返回新的State。

let nextState = todoapp(previousState,action);

State一旦有變化,Store就會(huì)調(diào)用監(jiān)聽(tīng)函數(shù)。

store.subscribe(listener)

listener可以通過(guò)store.getState()得到當(dāng)前狀態(tài)。如果使用的是React,這時(shí)可以觸發(fā)重新渲染View。

function listener(){

let newState = store.getState();

compoent.setState(newState);

}




Store收到Action以后,必須給出 一個(gè)新的State,這樣View才會(huì)發(fā)生變化。這種State的計(jì)算過(guò)程叫做Reducer。

Reducer是一個(gè)函數(shù),store.dispatch方法會(huì)觸發(fā) Reducer 的自動(dòng)執(zhí)行。為此,Store 需要知道 Reducer 函數(shù),做法就是在生成 Store 的時(shí)候,將 Reducer 傳入createStore方法。

const defaultState = 0;

const reducer = (state = defaultState,action)=>{

switch(action.type){

case ‘ADD’:

return state + action.payload;

default:

returnstate;

}

}

import { createStore } from 'redux';

const store=createStore(reducer); ? ? ? ?//createStore用來(lái)生成Store

const state=store.getState(); ? ? ?//對(duì)Store生成快照(即數(shù)據(jù)集合State)

store.dispatch({ ? ? ? //store.dispatch是View發(fā)出Action的唯一方法

type:'ADD_TODO',

payload:'Learn Redux'

});

store.subscribe(listener); ? ?//store.subscribe方法設(shè)置監(jiān)聽(tīng)函數(shù),一旦State發(fā)生變化,就自動(dòng)執(zhí)行這個(gè)函數(shù)




重新整理(2016-12-9)

action-->reducer-->createStore

action:我們得用專門(mén)的處理函數(shù),在各個(gè)數(shù)據(jù)來(lái)源里篩選出我們真正需要的數(shù)據(jù),不把那些無(wú)關(guān)緊要的、甚至是臟的數(shù)據(jù)污染了我們的全局?jǐn)?shù)據(jù)對(duì)象。這種對(duì)數(shù)據(jù)來(lái)源做萃取工作的函數(shù),就叫action。

!!!action函數(shù)必須返回一個(gè)帶有type屬性的plain object

reducer:reducer就是迎接 action 函數(shù)返回的線索的「數(shù)據(jù)再處理函數(shù)」, action 是「預(yù)處理函數(shù)」。

createStore:




No.1 ?創(chuàng)建預(yù)處理,篩檢垃圾信息

No.2 根據(jù)action返回的信息,執(zhí)行對(duì)應(yīng)函數(shù)(對(duì)應(yīng)的函數(shù)在No.8里定義)

No.3 執(zhí)行createStore

No.4 設(shè)置路由?。。?!

No.5 配置目標(biāo)網(wǎng)站(根目錄)

No.6 編譯的入口文件

No.7 ajax文件

No.8 各頁(yè)面DOM

No.9 CSS樣式表

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容