【react】Redux源码解析

2020-09-07  本文已影响0人  SophieRabbit

Redux 源码

let createStore = (reducer) => {

    let state;

    //获取状态对象

    //存放所有的监听函数

    let listeners = [];

    let getState = () => state;

    let dispach = (action) => {     //提供一个方法供外部调用派发action

        state = reducer(state, action);        //调用管理员reducer得到新的state

        listeners.forEach((listener) => {

             listener()        //执行所有的监听函数

        })

    }  

    let subscribe = (listener) => {       // 订阅状态变化事件,当状态改变发生之后执行监听函数

        listeners.push(listener);

    }

    dispath();    // 初始化的调用派发action函数

    return {

        getState,

        dispath,

        subscribe

    }

}

let combineReducers = (reducers) => {

    // 传入一个reducers管理组,返回的是一个reducer

    return function(state={},action={}) {

        let newState = {};

        for(var attr in reducers) {

            newState[attr] = reducers[attr](state[attr],action)

        }

        return newState;

    }

}

export {createStore,combineReducers};

使用案例:

function createStore(reducer) {

    var state;

    var listeners = [];

    var getState = () => state;

    var dispatch = (action) => {

        state = reducer(state, action);

        listeners.forEach(lis => lis());    // 遍历执行监听函数

    }

    var subscribe = (listener) => {

        listeners.push(listener);

        return () => {

            listeners = listeners.filter((lis) => {     // 过滤掉当前的监听函数,避免重复订阅

                return lis != listener

            })

        }

    }

    dispatch();

    return {

        getState, dispatch, subscribe

    }

}

var reducer = (state = 0, action) => {     // 输入当前状态,与行为,返回新的状态

    if (!action) return state;

    console.log(action);

    switch (action.type) {

        case 'INCREMENT':

            return state + 1;

        case 'DECREMENT':

            return state - 1;

        default:

            return state;

    }

}

var store = createStore(reducer);

store.subscribe(function () {

    document.querySelector('#counter').innerHTML = store.getState();   // 订阅数据

});

document.querySelector('#addBtn').addEventListener('click', function () {

    store.dispatch({type: 'INCREMENT'});    //分发数据

});

document.querySelector('#minusBtn').addEventListener('click', function () {

    store.dispatch({type: 'DECREMENT'});    //分发数据

});

上一篇下一篇

猜你喜欢

热点阅读