一、Redux介紹 Redux的設計思想很簡單,就兩句話: 二、Redux基本概念和API Store Store就是保存數據(state)的地方,整個應用只能有一個Store。Redux通過createStore來生成store。 State Store對象包含所有State,某一時刻的數據集合就 ...
一、Redux介紹
Redux的設計思想很簡單,就兩句話:
- Web應用是一個狀態機,神力與狀態是一一對應的
- 所有的狀態,保存在一個對象裡面
二、Redux基本概念和API
- Store
Store就是保存數據(state)的地方,整個應用只能有一個Store。Redux通過createStore來生成store。
- State
Store對象包含所有State,某一時刻的數據集合就是State,可以用過store.getState()獲取。
Redux規定:一個state對應一個View,只要State相同,View就相同。
- Action
State變化,會導致View變化,用戶通過動作會觸發Action,告知State應該要發生變化了(State只能由Action改變)。
const action={ type:'Exp1', otherParam:'1' };
上面代碼中,Action的名稱是Exp1,攜帶的信息是1。
View發送Action的方法是store.dispatch(action)
Store收到Action後,需要能過Reducer更新Store里的State,Reducer是一個函數,它接受Action和當前State作為參數,返回一個新的State
整個流程圖如下圖:
- 純函數
所謂的純函數是指同樣的輸入,必定得到同樣的輸出,Reducer函數就是純函數,純函數有以下約束:
- 不得改寫參數
- 不能調用系統I/O的API
- 不能調用Date.now()或者Math.random()等不純的方法,因為每次都會得到不一樣的結果
由於Reducer是純函數,就可以保證同樣的State必定得到同樣的View。但也正因為這一點,Reducer函數裡面不能改變State,必須返回一個全新的對象,請參考下麵的寫法
// State 是一個對象 function reducer(state, action) { return Object.assign({}, state, { thingToChange }); // 或者 return { ...state, ...newState }; } // State 是一個數組 function reducer(state, action) { return [...state, newItem]; }
- store.subscribe()
此方法用於監聽State狀態,一但State發生變化,就自動執行些函數
import { createStore } from 'redux'; const store = createStore(reducer); store.subscribe(listener);
store.subscribe
方法返回一個函數,調用這個函數就可以解除監聽。
三、Reducer的拆分
Reducer負責生成State,由於整個應用只有一個State對象,包含所有數據,這可能會造成Reducer函數非常龐大。請看下麵例子
const reducer=(state,action)=>{ const{type,otherParam}=action; switch(type){ case 1: return Object.assign({},state,{ chatLog:state.chatLog.concat(otherParam) }); case 2: return Object.assign({},state,{ statusMessage:otherParam }); ......... } }
拆分:
const reducer={state,action}=>{ return{ chatLog:chatLog(state.chatLog,action), statusMessage:statusMessage(state,statusMessage,action), ............... } }
拆分後需要通過方法combineReducers進行合併:
reducer=combineReducers({
chatLog,
statusMessage,
userName
})