美文网首页WEB前端程序开发Web 前端开发
一个简单的 Redux Store 表示法

一个简单的 Redux Store 表示法

作者: 牧秦丶 | 来源:发表于2018-06-21 14:51 被阅读1次

1. createStore

首先定义 createStore 用于创建一个 store:

const createStore = ({ reducers = {}, initialState }) => {
  let state = initialState;
  let listeners = [];

  const getState = () => state;

  const dispatch = ({ type, data }) => {
    const reducer = reducers[type];
    if (reducer) {
      state = reducer(state, data);
    }

    listeners.forEach(listener => listener(state));
  };

  const subscribe = (listener) => {
    listeners.push(listener);
    return () => {
      listeners = listeners.filter(l => l !== listener);
    }
  };

  return {
    getState,
    dispatch,
    subscribe
  };
};

2. 使用

// 1. create store with initialState and reducers
const store = createStore({
  initialState: [],

  reducers: {
    add: (state, data) => {
      return [
        ...state,
        data,
      ];
    },
    remove: (state, data) => {
      return state.filter(c => c.id !== data.id);
    }
  },
});

// 2. subscribe listeners
const unSubscriber = store.subscribe(printState);

// 3. dispatch actions.
store.dispatch({ type: 'add', data: { id: 1, content: 'Article' } });
store.dispatch({ type: 'add', data: { id: 2, content: 'HaHa' } });
store.dispatch({ type: 'remove', data: { id: 2 } });

// 4. unsubscribe listener
unSubscriber();

// 5. print current state.
printState(store.getState());

3. 运行结果:

results

相关文章

网友评论

    本文标题:一个简单的 Redux Store 表示法

    本文链接:https://www.haomeiwen.com/subject/jtnqyftx.html