一个极简的React-Hooks状态管理库的实现

前端技术的发展日新月异,vue,react,angular等的兴起,为我们带来了新的开发体验。但随着技术的革新,以及前端页面复杂度的提升,对应有localStorage,eventBus,vuex,redux,mobx,rxjs等数据存储和管理的方案,所以觉得研究状态管理还是很有必要的。

当然,使用Hooks自带的useContext + useReducer也是可以的.只是:

每次都得创建createContext和useReducer模板代码, 稍显麻烦 !!!
1
2
3
4
5
6
7
8
9
10
11
12
import React, { createContext } from "react";

// 创建 context
export const ColorContext = createContext({});

export const Color = props => {
return (
<ColorContext.Provider value={{ color: "blue" }}>
{props.children}
</ColorContext.Provider>
);
};

创建reducer

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
// color.js
import React, { createContext, useReducer } from "react";

// 创建 context
export const ColorContext = createContext({});

// reducer
export const UPDATE_COLOR = "UPDATE_COLOR"
const reducer = (state, action) => {
switch(action.type) {
case UPDATE_COLOR:
return action.color
default:
return state
}
}

/**
* 创建一个 Color 组件
* Color 组件包裹的所有组件都可以访问到 value
*/
export const Color = props => {
const [color, dispatch] = useReducer(reducer, 'blue')
return (
<ColorContext.Provider value={{color, dispatch}}>
{props.children}
</ColorContext.Provider>
);
};

更新状态

为按钮添加点击事件,调用 dispatch 就可以更新颜色了。

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
import React, { useContext } from "react";
import { colorContext, UPDATE_COLOR } from "./color";

const Buttons = props => {
const { dispatch } = useContext(colorContext);
return (
<React.Fragment>
<button
onClick={() => {
dispatch({ type: UPDATE_COLOR, color: "red" });
}}
>
红色
</button>
<button
onClick={() => {
dispatch({ type: UPDATE_COLOR, color: "yellow" });
}}
>
黄色
</button>
</React.Fragment>
);
};

export default Buttons;

useStore

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
import React, { useEffect } from "react";
import { render } from "react-dom";
import useStore, { createStore, useLocalStore } from "./store-src/index";

import "./styles.css";

const counterStore = createStore(
{
count: 0,
num: 'ABCD'
},
{
increment: (state) => ({ ...state, ...{ count: state.count + 1 } }),
decrement: (state) => ({ ...state, ...{ count: state.count - 1 } }),
increment2: (state, num) => ({ ...state, ...{ count: state.count + num } }),
decrement2: (state, num) => ({ ...state, ...{ count: state.count - num } }),
random: (state) => ({
...state, ...{
count: Math.round(Math.random() * 10)
}
}),
async incrementAsync(state, num) {
const promise = new Promise((resolve) => setTimeout(resolve, 3000));
await promise;
return { ...state, ...{ count: state.count + 10 } };
},
}
);

const Counter = () => {
const {
state: { count, num },
actions
} = useStore(counterStore);

return (
<>
<h1>Counter</h1>
<h2>Count {count}-{num}</h2>
<button onClick={() => actions.decrement()}>-</button>
<button onClick={() => actions.increment()}>+</button>
</>
);
};

const LocalCounter = () => {
const {
state: { count },
actions
} = useLocalStore(counterStore);

useEffect(() => {
actions.random();
}, []);

return (
<>
<h1>Local Counter</h1>
<h2>Count {count}</h2>
<button onClick={() => actions.decrement()}>-</button>
<button onClick={() => actions.increment()}>+</button>
</>
);
};


const LocalCounter2 = () => {
const {
state: { count },
actions
} = useLocalStore(counterStore);

useEffect(() => {
actions.random();
}, []);

return (
<>
<h1>Local Counter add num</h1>
<h2>Count {count}</h2>
<button onClick={() => actions.decrement2(3)}>-</button>
<button onClick={() => actions.increment2(3)}>+</button>
<button onClick={() => actions.incrementAsync(3)}>异步3s加10</button>
</>
);
};

function App() {
return (
<div className="App">
<h1>useStore</h1>
<h2>一个极简的hooks状态管理</h2>
<Counter />
<Counter />
<LocalCounter />
<LocalCounter2 />
</div>
);
}

const rootElement = document.getElementById("root");
render(<App />, rootElement);

useStore源码 useStore

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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
// index.tsx
import { useState, useEffect, SetStateAction, Dispatch } from "react";
import usePromise from "./usePromise";

export type SetStateFunction<S = any> = Dispatch<SetStateAction<S>>;

const deepClone = (obj: any): any => {
if (!(obj instanceof Object) || obj instanceof Function) {
return obj;
}
if (Array.isArray(obj)) {
const arrayObj = new Array(obj.length);
for (let i = 0; i < obj.length; i++) {
arrayObj[i] = deepClone(obj[i]);
}
return arrayObj;
}
if (obj instanceof Date) {
return new Date(obj.getTime());
}
if (obj instanceof RegExp) {
return new RegExp(obj.source);
}
const clone: any = {};
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
clone[key] = deepClone(obj[key]);
}
}
return clone;
};

type StoreInternal = {
initialState: any;
setStateSet: Set<SetStateFunction>;
setters: Record<string, any>;
getters: Record<string, any>;
reducers: ReducerFunctions<any>;
actions: any;
utils: ReducerUtils<any>;
};

export type AsyncState<T> = {
loading: boolean;
error?: object | string;
data: T;
};

export type AsyncAction<S> = <T extends keyof S, B>(
key: T,
promise: Promise<B>,
throwError?: boolean
) => S[T] extends
| AsyncState<B>
| AsyncState<B | null>
| AsyncState<B | undefined>
? Promise<S>
: never;

type ReducerUtils<S> = {
setState: SetStateFunction<S>;
asyncAction: AsyncAction<S>;
reset: (...keys: (keyof S)[]) => S | Promise<S>;
receiveState: () => S;
};

export type Store<S, A> = {
state: S;
actions: A;
setState: SetStateFunction<S>;
};

type StateReceiver<S, A> = {
store: Store<S, A>;
receiveState: () => S;
setState: SetStateFunction<S>;
};

function asyncState<T>(): AsyncState<T | null>;
function asyncState<T>(data: T): AsyncState<T>;
function asyncState<T>(data?: T): AsyncState<T> | AsyncState<T | null> {
return {
data: data || null,
loading: false
};
}

const copyState: <S>(state: S) => any = state => {
// is primitive
if (!(state instanceof Object)) {
return state;
}
// is array
if (Array.isArray(state)) {
return [...state];
}

// is object
return {
...state
};
};

type StoreActions<S> = Record<string, (payload?: any) => Promise<S>>;

const mapActions: <S, R extends ReducerFunctions<S>>(
internals: StoreInternal,
reducers: R,
stateReceiver: StateReceiver<S, R>
) => StoreActions<S> = (internals, reducers, stateReceiver) => {
return Object.entries(reducers).reduce<StoreActions<any>>(
(acc, [key, reducer]) => {
acc[key] = async (payload: any) => {
const currentState = copyState(stateReceiver.receiveState());
if (window["GLOBAL_HOOK_DEBUG" as any]) {
// tslint:disable-next-line:no-console
console.log(`Invoking action: ${key}\n- State before:`, currentState);
}
const newState = await reducer(currentState, payload, internals.utils);
stateReceiver.setState(newState);
if (window["GLOBAL_HOOK_DEBUG" as any]) {
// tslint:disable-next-line:no-console
console.log(`Done invoking action: ${key}\n- State after:`, newState);
}
return newState;
};
return acc;
},
{}
);
};

const applySettersGetters = (internals: StoreInternal, state: any) => {
Object.entries(internals.setters).forEach(([k, setter]) => {
state.__defineSetter__(k, setter);
});
Object.entries(internals.getters).forEach(([k, getter]) => {
state.__defineGetter__(k, getter);
});
};

export type ReducerFunctions<S> = {
[key: string]: (
state: S,
payload: any,
utils: ReducerUtils<S>
) => Promise<S> | S;
};

export type EmptyReducerFunction<S> = () => Promise<S> | S;

export type StateReducerFunction<S> = (state: S) => Promise<S> | S;

type ExtractPayload<S, T> = T extends (
state: S,
payload: infer P
) => S | Promise<S>
? P
: T extends (
state: S,
payload: infer P,
utils: ReducerUtils<S>
) => S | Promise<S>
? P
: never;

function createStore<S, R>(
initialState: S,
reducers: R & ReducerFunctions<S>
): Store<
S,
{
[T in keyof R]: ExtractPayload<S, R[T]> extends undefined | null
? () => Promise<S>
: R[T] extends StateReducerFunction<S>
? () => Promise<S>
: R[T] extends EmptyReducerFunction<S>
? () => Promise<S>
: (payload: ExtractPayload<S, R[T]>) => Promise<S>;
}
>;
function createStore<S>(
initialState: S,
...reducerArray: any[]
): Store<S, any> {
const reducers = reducerArray.reduce<ReducerFunctions<any>>((acc, curr) => {
Object.keys(curr).forEach(key => {
acc[key] = curr[key];
});
return acc;
}, {});

const internals: StoreInternal = {
reducers,
initialState: deepClone(initialState),
setStateSet: new Set(),
setters: {},
getters: {},
actions: {},
utils: {} as any
};
const setState = (state: any) => {
applySettersGetters(internals, state);
actionStore.state = state;
internals.setStateSet.forEach(setStateFunction => {
setStateFunction(state);
});
};

if (initialState instanceof Object) {
Object.keys(initialState).forEach(key => {
const setter = (initialState as any).__lookupSetter__(key);
const getter = (initialState as any).__lookupGetter__(key);
if (setter) {
internals.setters[key] = setter;
}
if (getter) {
internals.getters[key] = getter;
}
});
}

const actionStore = {
setState,
state: initialState,
actions: {},
["__internal"]: internals
};

const stateReceiver = {
setState,
receiveState: () => actionStore.state,
store: actionStore
};

internals.utils = {
setState: stateReceiver.setState,
asyncAction: async (
key: string | number | symbol,
promise: Promise<any>,
throwError = false
) => {
if (window["GLOBAL_HOOK_DEBUG" as any]) {
console.log("- Async action start:", key);
}
let state = stateReceiver.receiveState() as any;
let asyncStateObj = state[key] as AsyncState<any>;
delete asyncStateObj.error;
asyncStateObj.loading = true;
stateReceiver.setState({ ...state, [key]: asyncStateObj });
try {
const data = await promise;
asyncStateObj = {
data,
loading: false
};
if (window["GLOBAL_HOOK_DEBUG" as any]) {
console.log("- Async action complete:", key);
}
} catch (error) {
asyncStateObj.loading = false;
asyncStateObj.error = error;
if (window["GLOBAL_HOOK_DEBUG" as any]) {
console.error("- Async action error:", key);
}
if (throwError) {
throw error;
}
}

state = stateReceiver.receiveState() as any;
return { ...state, [key]: asyncStateObj };
},
reset: (...keys) => {
if (window["GLOBAL_HOOK_DEBUG" as any]) {
console.log("Calling store reset for:", keys);
}
if (keys.length === 0) {
return deepClone(internals.initialState);
}
const state = stateReceiver.receiveState() as any;
const resetedState: any = {};
keys.forEach(a => {
resetedState[a] = internals.initialState[a];
});
return { ...state, ...deepClone(resetedState) };
},
receiveState: stateReceiver.receiveState
};

const actions = mapActions(internals, reducers, stateReceiver);

actionStore.actions = actions;
internals.actions = actions;

return actionStore;
}

const useStore: <S, A>(store: Store<S, A>) => Store<S, A> = store => {
const [_, setState] = useState(store.state);

const internals = (store as any)["__internal"] as StoreInternal;
const setters = internals.setStateSet;

useEffect(() => {
setters.add(setState);
}, [setters]);

useEffect(
() => () => {
setters.delete(setState);
},
[setters]
);

return store;
};

const useLocalStore: <S, A>(store: Store<S, A>) => Store<S, A> = store => {
const internals = (store as any)["__internal"] as StoreInternal;
const [sa, internalSetState] = useState(() => {
// tslint:disable-next-line:no-shadowed-variable
const stateReceiver = {
store: {} as Store<any, any>,
receiveState: () => store.state,
// eslint-disable-next-line @typescript-eslint/no-empty-function
setState: (s: any) => { }
};
return {
stateReceiver,
state: store.state,
actions: mapActions(internals, internals.reducers, stateReceiver) as any
};
});

useEffect(
() => () => {
// eslint-disable-next-line @typescript-eslint/no-empty-function
sa.stateReceiver.setState = (s: any) => { };
},
[sa.stateReceiver]
);

const { state, actions, stateReceiver } = sa;

const receiver = () => {
return state;
};

stateReceiver.receiveState = receiver;

const setState = (newState: any) => {
applySettersGetters(internals, newState);
internalSetState({
actions,
stateReceiver,
state: newState
});
};

const actionStore = {
state,
setState,
actions
};

stateReceiver.setState = setState;
stateReceiver.store = actionStore;

return actionStore;
};

function useStoreReset<S, A>(
store: Store<S, A>,
...keys: Array<keyof S>
): void {
useEffect(
() => () => {
const internals = (store as any)["__internal"] as StoreInternal;
internals.utils.setState(internals.utils.reset.apply(null, keys));
},
[store, keys]
);
}

export default useStore;
export { useLocalStore, asyncState, createStore, useStoreReset, usePromise };
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
// usePromise.ts
import { useState, useCallback } from "react";

type State<T> = {
data?: T;
error?: any;
loading: boolean;
};

type PromiseReturnType<T> = T extends (...args: any) => Promise<infer R>
? R
: never;

type PromiseCall<T> = T extends (...args: infer A) => Promise<infer R>
? (...args: A) => Promise<R>
: never;

const INITIAL_STATE = {
data: undefined,
error: undefined,
loading: false
};

export const usePromise: <T extends (...args: any) => Promise<any>>(
asyncFunction: T
) => [
State<PromiseReturnType<T>>,
PromiseCall<T>,
() => void
] = asyncFunction => {
const [state, setState] = useState<State<any>>(INITIAL_STATE);

const reset = useCallback(() => {
setState(INITIAL_STATE);
}, [setState]);

const call = useCallback(
(...args: any) =>
new Promise((resolve, reject) => {
setState({ loading: true });
let mounted = true;
(asyncFunction as any)(...args)
.then((data: any) => {
if (mounted) {
setState({ data, loading: false });
resolve(data);
}
})
.catch((error: any) => {
if (mounted) {
setState({ error, loading: false, data: undefined });
reject(error);
}
});
return () => {
mounted = false;
};
}),
[asyncFunction, setState]
);

return [state, call as any, reset];
};

export default usePromise;

其他