Redux 基本实现

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
function createStore(reducer) {
let state, listener = [], getState, dispatch, subscribe;
dispatch = action => {
state = reducer(state, action)
listener.forEach(item => item())
}
dispatch({})
subscribe = fn => {
listener = [...listener, fn]
return () => {
listener = listener.filter(item => item !== fn)
}
}
getState = () => JSON.parse(JSON.stringify(state))
return {dispatch, getState, subscribe}
}
/**
* combineReducers 合并reducers
* @param reducers[Object] 接收一个对象
* @returns {function()}
*/
function combineReducers(reducers) {

return (state = {}, action) => {
let obj = {}
for (let key in reducers) {
if(!reducers.hasOwnProperty(key)) continue;
obj[key] = reducers[key](state[key], action)
}
return obj
}
}

/**
* bindActionCreators 合并actions返回使用dispatch包装的结果
* @param actions
* @param dispatch
* @returns {{}}
*/
function bindActionCreators(actions,dispatch) {
//将actions 包装成 mapDispatchToProps返回的对象

let obj={};
for(let key in actions){
if(!actions.hasOwnProperty(key)) continue;
obj[key]=(...arg)=>{
dispatch(actions[key](...arg))
}
}
return obj;

}