Redux核心概念

設(shè)計(jì)思想
(1) Web 應(yīng)用是一個(gè)狀態(tài)機(jī),視圖與狀態(tài)是一一對(duì)應(yīng)的
(2) 所有的狀態(tài)都保存在一個(gè)對(duì)象里面(store)
設(shè)計(jì)原則
Dan Abramov 在推特上多次強(qiáng)調(diào),Redux 的設(shè)計(jì)是以幾個(gè)原則為優(yōu)先的:
要讓狀態(tài)的變化可追蹤,可重復(fù),可維護(hù)。
Redux 認(rèn)為,一個(gè)應(yīng)用程序中,所有應(yīng)用模塊之間需要共享訪問的數(shù)據(jù),都應(yīng)該放在 State 對(duì)象中。
基本概念
1、Store:
保存數(shù)據(jù)的地方、像一個(gè)倉(cāng)庫(kù)、保存著需使用的數(shù)據(jù)
redux提供createStore生成store
import { createStore } from 'redux';
const store = createStore(fn);
2、State:
組件狀態(tài)數(shù)據(jù)
redux提供store.getState()獲得
import { createStore } from 'redux';
const store = createStore(fn);
const state = store.getState();
Redux 規(guī)定, 一個(gè) State 對(duì)應(yīng)一個(gè) View。只要 State 相同,View 就相同。你知道 State,就知道 View 是什么樣,反之亦然。
3、Action:
State 的變化,會(huì)導(dǎo)致 View 的變化。但是,用戶接觸不到 State,只能接觸到 View。所以,State 的變化必須是 View 導(dǎo)致的。Action 就是 View 發(fā)出的通知,表示 State 應(yīng)該要發(fā)生變化了。
Action 是一個(gè)對(duì)象。
const action = {
type: 'action_name', // 必須的,action的名稱
payload: 'somedata' //攜帶的信息
};
4、Reducer
store收到action后,給出一個(gè)新的state,然后View才會(huì)發(fā)生變化。 State 的計(jì)算過程就叫做 Reducer。
Reducer 是一個(gè)函數(shù)
const reducer = function (state, action) { // 接受倆參數(shù)當(dāng)前State和Action
// ...
return new_state; // 返回新的state
};
實(shí)際例子:
const defaultState = 0;
const reducer = (state = defaultState, action) => {
switch (action.type) {
case 'ADD':
return state + action.payload;
default: return state;
}
};
const state = reducer(1, { type: 'ADD', payload: 2}); // 實(shí)際應(yīng)用中無(wú)需這樣手動(dòng)調(diào)用,store.dispatch
方法會(huì)觸發(fā) Reducer 的自動(dòng)執(zhí)行
上面代碼中,reducer函數(shù)收到名為ADD的 Action 以后,就返回一個(gè)新的 State,作為加法的計(jì)算結(jié)果。
實(shí)際應(yīng)用中,Reducer 函數(shù)不用像上面這樣手動(dòng)調(diào)用,store.dispatch方法會(huì)觸發(fā) Reducer 的自動(dòng)執(zhí)行。
因此Store 需要知道 Reducer 函數(shù),做法就是在生成 Store 的時(shí)候,將 Reducer 傳入createStore
方法。
import { createStore } from 'redux';
const store = createStore(reducer);
上面代碼中,createStore接收Reducer作為參數(shù),生成新的store。
之后每當(dāng)store.dispatch發(fā)送一個(gè)新的Action就會(huì)自動(dòng)調(diào)用Reducer,得到新的State。
5、Reducer 的拆分
使用combineReducers()
import { combineReducers } from 'redux';
import PostsReducer from './reducer_posts';
import { reducer as formReducer } from 'redux-form';
const rootReducer = combineReducers({
posts: PostsReducer,
form: formReducer
});
export default rootReducer;
React-Redux流程
首先,用戶發(fā)出Action
store.dispatch(action);
然后,Store調(diào)用Reducer,傳入兩個(gè)參數(shù):當(dāng)前 State 和收到的 Action。 Reducer 會(huì)返回新的 State 。
State 一旦有變化,Store 就會(huì)調(diào)用監(jiān)聽函數(shù)。
// 設(shè)置監(jiān)聽函數(shù)store.subscribe(listener);
listener
可以通過store.getState()
得到當(dāng)前狀態(tài)。如果使用的是 React,這時(shí)可以觸發(fā)重新渲染 View。
function listerner() {
let newState = store.getState();
component.setState(newState);
}
講了這么多、估計(jì)到了實(shí)際項(xiàng)目就又不知道什么是什么了,于是畫了下面的圖、希望能看懂 - -
