-
Notifications
You must be signed in to change notification settings - Fork 0
/
redux.js
56 lines (53 loc) · 1.36 KB
/
redux.js
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
// reducer:传入初始状态和计算逻辑
// enhancer:传入增强函数,比如中间件
function createStore(reducer, enhancer) {
if (enhancer) {
return enhancer(createStore)(reducer)
}
// 初始化状态
let state = reducer(undefined, { type: '__INIT__' })
// 初始化监听器列表
let listeners = []
return {
dispatch: (action) => {
state = reducer(state, action)
// 更改状态后调用所有监听器
listeners.forEach((listener) => listener())
},
getState: () => state,
subscribe: (listener) => {
listeners.push(listener)
},
}
}
// 应用中间件
function applyMiddleware(...middlewares) {
return (createStore) => (reducer) => {
const store = createStore(reducer)
const middlewareApi = {
getState: store.getState,
dispatch: (action, ...args) => dispatch(action, ...args),
}
const dispatchChain = middlewares.map((middleware) =>
middleware(middlewareApi)
)
const composedMiddleware = compose(...dispatchChain)
const dispatch = composedMiddleware(store.dispatch)
return {
...store,
dispatch,
}
}
}
// lib: compose函数
function compose(...functions) {
if (functions.length === 0) {
return (arg) => arg
}
return functions.reduce((a, b) => (arg) => a(b(arg)))
}
const Redux = {
applyMiddleware,
compose,
createStore,
}