Appearance
redux工程化
redux工程化其实就是“按模块划分”

action-types.js
JavaScript
/* 投票 */
export const VOTE_SUP = 'VOTE_SUP';
export const VOTE_OPP = 'VOTE_OPP';
1
2
3
2
3
reducers
JavaScript
// 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;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
actions
JavaScript
// 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;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
index.js
JavaScript
import { createStore } from 'redux';
import reducer from './reducers';
/* 创建STORE */
const store = createStore(reducer);
export default store;
1
2
3
4
5
6
2
3
4
5
6
在组件中需要修改的地方
JavaScript
// 获取指定模块的状态
let { supNum, oppNum } = store.getState().vote;
// 派发任务的时候
import actions from '@/store/actions';
...
store.dispatch(actions.vote.support(10));
store.dispatch(actions.vote.oppose());
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
combineReducers源码
JavaScript
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;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13