码迷,mamicode.com
首页 > 其他好文 > 详细

[Redux] Implementing Store from Scratch

时间:2015-11-26 06:56:22      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:

Learn how to build a reasonable approximation of the Redux Store in 20 lines. No magic!

 

const counter = (state = 0, action) => {
  switch (action.type) {
    case ‘INCREMENT‘:
      return state + 1;
    case ‘DECREMENT‘:
      return state - 1;
    default: 
      return state;
  }
}

const createStore = (reducer) => {
  let state;
  let listeners = [];
  
  const getState = () => state;
  
  const dispatch = (action) => {
    state = reducer(state, action);
    listeners.forEach(listener => listener());
  };
  
  const subscribe = (listener) => {
    listeners.push(listener);
    return () => {
      listeners = listeners.filter(l => l !== listener);
    };
  };
  
  dispatch({});
  
  return { getState, dispatch, subscribe };
};

const store = createStore(counter);

const render = () => {
  document.body.innerText = store.getState();
};

store.subscribe(render);
render();

document.addEventListener(‘click‘, () => {
  store.dispatch({ type: ‘INCREMENT‘ });
});

 

[Redux] Implementing Store from Scratch

标签:

原文地址:http://www.cnblogs.com/Answer1215/p/4996485.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!