Skip to content
On this page

Redux源码解读

JavaScript
import _ from '@/assets/utils';

export const createStore = function createStore(reducer) {
    let state,
        listeners = [];

    // 获取状态
    const getState = function getState() {
        return _.clone(true, state);
    };

    // 事件池管理
    const subscribe = function subscribe(listener) {
        if (typeof listener !== 'function') {
            throw new Error(`Expected the listener to be a function.`);
        }
        if (listeners.some(item => item === listener)) return;
        listeners.push(listener);

        return () => {
            listeners.filter(item => item !== listener);
        };
    };

    // 任务派发
    const dispatch = function disptach(action) {
        if (!_.isPlainObject(action)) {
            throw new Error("Actions must be plain objects.");
        }
        if (typeof action.type === 'undefined') {
            throw new Error('Actions may not have an undefined "type" property. You may have misspelled an action type string constant.');
        }
        // 修改状态
        try {
            state = reducer(state, action);
        } catch (_) { }

        // 通知事件池中的方法执行
        listeners.forEach(listener => {
            if (typeof listener === "function") {
                listener()
            }
        });

        return action;
    };

    // 默认派发执行一次:设置状态初始值
    const randomString = function randomString() {
        return Math.random().toString(36).substring(7).split('').join('.');
    };
    dispatch({
        type: `@@redux/INIT${randomString()}`
    });

    return {
        getState,
        subscribe,
        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
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
沪ICP备20006251号-1