0%

写一个自己的redux

写一个自己的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
53
54
55
56
57
58
function createStore (reducer, preState, enhancer) {
if (enhancer && typeof enhancer === 'function') {
return enhancer(createStore)(reducer,preState)
}
let currentReducer = reducer
let currentState = preState
const listeners = []
const getState = () => currentState
const subscribe = (listener) => {
listeners.push(listener)
const unsubscribe = () => listeners.splice(listeners.indexOf(listener),1)
return {
unsubscribe
}
}
const dispatch = (action) => {
currentState = currentReducer(currentState,action)
listeners.forEach(listener => listener())
return action
}
return {
getState,
subscribe
}
}

function compose (...funcs) {
if(funcs.length === 0) return arg => arg
if(funcs.length === 1) return funcs[0]
return funcs.reduce((x,y)=>(...args) => x(y(...args)))
}

function applyMiddleware (...middlewares) {
return createStore => (...args) {
const store = createStore(...args)
let dispatch = () => {}
const middlewareApi = {
getState: store.getState,
dispatch: (...args) => dispatch(...args)
}
const chain =middlewares.map(middleware => middleware(middlewareApi))
dispatch = compose(...chain)(store.dispatch)
return {
...store,
dispatch
}
}
}

function thunkMiddleware () {
return ({dispatch,getState}) => next => action => {
if(typeof action === 'function'){
return action(dispatch,getState)
}
return next(action)
}
}
const thunk = thunkMiddleware()