redux工程化
redux工程化其实就是“按模块划分”
action-types.js
/* 投票 */
export const VOTE_SUP = 'VOTE_SUP';
export const VOTE_OPP = 'VOTE_OPP';
reducers
// voteReducer.js
import { VOTE_SUP, VOTE_OPP } from '../action-types';
import _ from '@/assets/utils';
let initialState = {
supNum: 10,
oppNum: 5
};
export default function voteReducer(state = initialState, action) {
state = _.clone(true, state);
let { type, payload = 1 } = action;
switch (type) {
case VOTE_SUP:
state.supNum += payload;
break;
case VOTE_OPP:
state.oppNum += payload;
break;
default:
}
return state;
};
// index.js
import { combineReducers } from 'redux';
import voteReducer from './voteReducer';
/*
state公共状态
vote
supNum: 10,
oppNum: 5
*/
const reducer = combineReducers({
vote: voteReducer
});
export default reducer;
actions
// voteAction.js
import { VOTE_SUP, VOTE_OPP } from '../action-types';
const voteAction = {
support(payload) {
return {
type: VOTE_SUP,
payload
};
},
oppose() {
return {
type: VOTE_OPP
};
}
};
export default voteAction;
// index.js
import voteAction from "./voteAction";
const actions = {
vote: voteAction
};
export default actions;
index.js
import { createStore } from 'redux';
import reducer from './reducers';
/* 创建STORE */
const store = createStore(reducer);
export default store;
在组件中需要修改的地方
// 获取指定模块的状态
let { supNum, oppNum } = store.getState().vote;
// 派发任务的时候
import actions from '@/store/actions';
...
store.dispatch(actions.vote.support(10));
store.dispatch(actions.vote.oppose());
combineReducers源码
export default function combineReducers(reducers) {
const reducerKeys = Reflect.ownKeys(reducers);
return function combination(state = {}, action) {
const nextState = {};
for (let i = 0; i < reducerKeys.length; i++) {
const key = reducerKeys[i],
reducer = reducerKeys[key];
const nextStateForKey = reducer(state[key], action);
nextState[key] = nextStateForKey;
}
return nextState;
}
}