-
Notifications
You must be signed in to change notification settings - Fork 0
/
Redux实现.html
309 lines (271 loc) · 10.5 KB
/
Redux实现.html
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Redux实现</title>
</head>
<body>
<div></div>
<p></p>
<button>增加</button>
<button>减少</button>
<button>无效</button>
<button>修改</button>
<script>
const createStore = function (reducer, initState, enhancer) {
// 检查你的 state 和 enhancer 参数有没有传反
if (typeof initState === 'function' && typeof enhancer === 'undefined') {
enhancer = initState
initState = undefined
}
// 如果有传入合法的 enhancer, 则通过 enhancer 再调用一次 createStore
if (typeof enhancer !== 'undefined') {
if (typeof enhancer !== 'function') {
throw new Error('Expected the enhancer to be a function.')
}
return enhancer(createStore)(reducer, initState)
}
let state = initState;
let listeners = [];
function subscribe(listener) {
listeners.push(listener);
return function unsubscribe() {
const index = listeners.indexOf(listener)
listeners.splice(index, 1)
}
}
function dispatch(action) {
state = reducer(state, action);
for (let i = 0; i < listeners.length; i++) {
const listener = listeners[i];
listener();
}
}
function getState() {
return state;
}
function replaceReducer(nextReducer) {
reducer = nextReducer
/*刷新一遍 state 的值,新来的 reducer 把自己的默认状态放到 state 树上去*/
dispatch({ type: Symbol() })
}
dispatch({ type: Symbol() })
return {
subscribe,
dispatch,
getState,
replaceReducer
}
}
function combineReducers(reducers) {
const reducerKeys = Object.keys(reducers)
// console.log(reducerKeys) /* reducerKeys = ['counter', 'info']*/
/*返回合并后的新的reducer函数*/
return function combination(state = {}, action) {
/*生成的新的state*/
let nextState = {}
/*遍历执行所有的reducers,整合成为一个新的state*/
for (let i = 0; i < reducerKeys.length; i++) {
const key = reducerKeys[i]
const reducer = reducers[key]
/*之前的 key 的 state*/
const previousState = state[key]
/*执行 分 reducer,获得新的state*/
const nextStateForKey = reducer(previousState, action)
nextState[key] = nextStateForKey
}
console.log(nextState)
return nextState;
}
}
function applyMiddleware(...middlewares) {
/*返回一个重写createStore的方法*/
return function (createStore) {
/*返回重写后新的 createStore*/
return function (reducer, initState, enhancer) {
/*1. 生成store*/
const store = createStore(reducer, initState, enhancer);
/*给每个 middleware 传下store,相当于 const logger = loggerMiddleware(store);*/
/* const chain = [exception, time, logger]*/
const chain = middlewares.map(middleware => middleware(store));
let dispatch = store.dispatch;
/* 实现 exception(time((logger(dispatch))))*/
chain.reverse().map(middleware => {
dispatch = middleware(dispatch);
});
/*2. 重写 dispatch*/
store.dispatch = dispatch;
return store;
}
}
}
/*核心的代码在这里,通过闭包隐藏了 actionCreator 和 dispatch*/
function bindActionCreator(actionCreator, dispatch) {
return function () {
return dispatch(actionCreator.apply(this, arguments))
}
}
/* actionCreators 必须是 function 或者 object */
function bindActionCreators(actionCreators, dispatch) {
if (typeof actionCreators === 'function') {
return bindActionCreator(actionCreators, dispatch)
}
if (typeof actionCreators !== 'object' || actionCreators === null) {
throw new Error()
}
const keys = Object.keys(actionCreators)
const boundActionCreators = {}
for (let i = 0; i < keys.length; i++) {
const key = keys[i]
const actionCreator = actionCreators[key]
if (typeof actionCreator === 'function') {
boundActionCreators[key] = bindActionCreator(actionCreator, dispatch)
}
}
return boundActionCreators
}
</script>
<script>
/* ====================================================== test ======================================================================== */
// let initState = {
// counter: {
// count: 0
// },
// info: {
// name: '无线研发',
// description: '我们都是前端爱好者!'
// }
// }
/* ===================================== reducer ======================================== */
let initState = {
count: 0
}
function counterReducer(state, action) {
/*注意:如果 state 没有初始值,那就给他初始值!!*/
if (!state) {
state = initState;
}
switch (action.type) {
case 'INCREMENT':
return {
count: state.count + (action.count || 1)
}
case 'DECREMENT':
return {
...state,
count: state.count - 1
}
default:
return state;
}
}
/* ===================================== reducer ======================================== */
let info = {
name: '无线研发',
description: '我们都是前端爱好者!'
}
function infoReducer(state, action) {
if (!state) {
state = info;
}
switch (action.type) {
case 'SET_NAME':
return {
...state,
name: action.name
}
case 'SET_DESCRIPTION':
return {
...state,
description: action.description
}
default:
return state;
}
}
const reducer = combineReducers({
counter: counterReducer,
info: infoReducer
});
/* ================================== 创建一个唯一的 store ===================================== */
// 中间件
const loggerMiddleware = (store) => (next) => (action) => {
console.log('====== logger =======')
// console.log('this state', store.getState());
// console.log('action', action);
next(action);
// console.log('next state', store.getState());
// console.log('====== logger =======')
}
let store = createStore(reducer, applyMiddleware(loggerMiddleware));
// console.log(store.getState())
/* ================================== actionCreator ===================================== */
function increment(count) {
return {
type: 'INCREMENT',
count
}
}
function setName(name) {
return {
type: 'SET_NAME',
name: name
}
}
function setDescription(description) {
return {
type: 'SET_DESCRIPTION',
description: description
}
}
// const actions = {
// increment: function () {
// return store.dispatch(increment.apply(this, arguments))
// },
// setName: function () {
// return store.dispatch(setName.apply(this, arguments))
// }
// }
const actions = bindActionCreators({ increment, setName, setDescription }, store.dispatch)
/* ================================== view ===================================== */
var btn = document.querySelectorAll('button')
var div = document.querySelector('div')
var p = document.querySelector('p')
div.innerText = store.getState().counter.count
p.innerText = JSON.stringify(store.getState().info)
/* ======================== 订阅变化,重新渲染DOM ======================== */
store.subscribe(() => {
let state = store.getState();
console.log('====== state change =====', state);
div.innerText = store.getState().counter.count
p.innerText = JSON.stringify(store.getState().info)
});
/* ================================== dispatch ===================================== */
/*增加*/
btn[0].addEventListener('click', function () {
store.dispatch(increment());
})
/*减少*/
btn[1].addEventListener('click', function () {
store.dispatch({
type: 'DECREMENT'
});
})
/*无效的动作!*/
btn[2].addEventListener('click', function () {
store.dispatch({
type: 'NONE',
count: 'abc'
});
})
/*修改名称*/
btn[3].addEventListener('click', function () {
actions.increment(100)
actions.setName('北京无线开发')
actions.setDescription('我们都是大佬')
})
</script>
</body>
</html>