mini-redux

说明

以最简单的方式实现核心 redux

源码

用法

miniRedux.test.ts
1
import createStore from '../../utility/algorithm/mini-redux/index';
2
3
describe('MiniRedux', () => {
4
interface IStaticState {
5
count: number;
6
};
7
interface IStaticAction {
8
type: string;
9
};
10
11
const initialState: IStaticState = {
12
count: 0,
13
};
14
const reducer = (state: IStaticState, action: IStaticAction) => {
15
switch (action.type) {
16
case 'INCREMENT': {
17
return {
18
...state,
19
count: ++state.count,
20
};
21
};
22
case 'DECREMENT': {
23
return {
24
...state,
25
count: --state.count,
26
};
27
};
28
default: {
29
return state
30
};
31
}
32
}
33
const store = createStore<IStaticState, IStaticAction>(reducer, initialState);
34
35
test('The method `store.getState()` should work fine', () => {
36
const state = store.getState();
37
38
expect(state.count).toBe(0);
39
});
40
test('The method `store.dispatch()` should work fine`', () => {
41
store.dispatch({
42
type: 'INCREMENT',
43
});
44
store.dispatch({
45
type: 'INCREMENT',
46
});
47
store.dispatch({
48
type: 'INCREMENT',
49
});
50
store.dispatch({
51
type: 'DECREMENT',
52
});
53
54
expect(store.getState().count).toBe(2);
55
});
56
test('The method `store.subscribe()` should work fine', () => {
57
let index = 0;
58
59
store.subscribe(() => {
60
++index;
61
});
62
store.dispatch({
63
type: 'DECREMENT',
64
});
65
store.dispatch({
66
type: 'DECREMENT',
67
});
68
69
expect(index).toBe(2);
70
expect(store.getState().count).toBe(0);
71
});
72
});
Copied!

API

Name
Type
Description
createStore
function
创建 store
dispatch
function
触发修改动作
getState
function
获取 state 数据
subscribe
function
监听 state 变化, 执行钩子函数
最近更新 1yr ago
复制链接