Redux reducer的作用
只用來處理state 變化,返回新的state
//previousState是初始化的state
//經(jīng)過reducer后,state變?yōu)閚extState
const someReducer = (previousState, action) =>{
return nextState;
}
reducer composition patten
reducer 組合模式---combineReducers的前身,直接看代碼
const initialState = {
count: 0,
alert: { visible: false, message: '' }
};
const rootReducer = (state = initialState, action) => ({
count: counterReducer(state.counter, action),
alert: alertReducer(state.alert, action)
});
- 拿一個(gè)總的rootReducer對象組合了兩個(gè)
count
和alert
對象
,這時(shí)state tree里有{count:counterReducer返回的state,alert:alertReducer返回的state},由于state tree保存在store中,所以現(xiàn)有的state保存在了store中
combineReducers
做了那么多鋪墊,現(xiàn)在說說combineReducers
1.是一種composition solution(前面提到過組合模式)的解決辦法,合并多個(gè)reducers為一個(gè)reducer
2.返回的是一個(gè)對象,這個(gè)對象可看出state tree filed names和管理該state的reducer之間的映射
3.形式是:
import {combineReducers} from '../lib/redux';
import count from './count';
import alert from './alert';
const rootReducer = combineReducers({
count:count
alert:alert
});
export default rootReducer;
This combineReducer call translates to: "our state tree consists of two different properties, count and alert, which will be handled by the counter and alert reducers respectively".
4.手動(dòng)實(shí)現(xiàn)combineReducers函數(shù)
import count from './count';
import alert from './alert';
//實(shí)現(xiàn)combineReducers函數(shù)
const combineReducers = (reducers) => {
return (state = {}, action) => {
return Object.keys(reducers).reduce((nextState, key) => {
//key: count,key
//state[key]:當(dāng)前遍歷的reducer先前的state值
//nextState[key]:當(dāng)前遍歷的reducer變化后的state值
nextState[key] = reducers[key](state[key], action);
return nextState;
}, {});
};
};
//調(diào)用combineReducers,傳入所有的reducers
const reducers = combineReducers({
count,
alert
})
export default reducers;
注意,reduce高階函數(shù)第二個(gè)參數(shù)初始為{},遍歷reducers的每個(gè)reducer,給nextState[key]賦值, 并push nextState到第二個(gè)參數(shù){}中.
每天努力一點(diǎn)點(diǎn)
謝謝你看完