redux的简单实现原理

字数 12阅读 274

redux的简单实现原理

function createStore(reducer) {
    let state;
    let getState = () => {
        return JSON.parse(JSON.stringify(state))
    };
    let listeners = [];
    let subScribe=fn => {
        listeners.push(fn);
        return fn => {
            listeners.filter(item => item!==fn)
        }
    };
    let dispatch = action => {
        state = reducer(state,action);
        listeners.forEach(item => item());
    };
    dispatch({});
    return {getState,dispatch,subScribe};
}
export {createStore}
  • action的写法
import * as Types from '../action-types';

export default {
  add(number) {
    return { type: Types.ADD, number };
  },
};
//这样直接导出,当做mapDispatch传给connect,需要dispatch的时候调用一下this.props.add就会触发自动调用dispatch

推荐阅读更多精彩内容