# 手写Redux
function createStore(reducer,defaultState) {
let state = defaultState
let currentReducer = reducer
function getState() {
return state
}
function dispatch(action) {
state = currentReducer(state,action)
listeners.forEach(fn => {
fn()
});
}
let listeners = []
function subscribe(fn) {
listeners.push(fn)
}
function replaceReducer(nextReducer){
currentReducer = nextReducer
dispatch({type: Symbol('')})
}
dispatch({ type: Symbol('') })
const store = {
getState,
dispatch,
subscribe
}
return store
}
function combineReducers(reducers){
const reducerKeys = Object.keys(reducers)
return function combination(state={},action) {
const nextState = {}
for (let i = 0; i < reducerKeys.length; i++) {
const key = reducerKeys[ i];
const reducer = reducers[key]
const previousState = state[key]
const nextForKeyState = reducer(previousState, action);
nextState[key] = nextForKeyState
}
return nextState;
}
}
function applyMiddleware(...middlewares) {
return function (createStore) {
return function (reducer, initState) {
const store = createStore(reducer, initState);
const simpleStore = { getState: store.getState };
const chain = middlewares.map((middleware) => middleware(simpleStore));
const dispatch = compose(...chain)(store.dispatch);
return {
...store,
dispatch,
};
};
};
}
function compose(...funcs) {
return funcs.reduce((a,b)=>(...args)=>a(b(args)))
}
function bindActionCreator(actionCreator, dispatch) {
return function () {
return dispatch(actionCreator.apply(this, arguments));
};
}
export default function bindActionCreators(actionCreators, dispatch) {
const boundActionCreators = {};
for (const key in actionCreators) {
const actionCreator = actionCreators[key];
if (typeof actionCreator === 'function') {
boundActionCreators[key] = bindActionCreator(actionCreator, dispatch);
}
}
return boundActionCreators;
}
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90