Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Redux] 简单实现 #164

Open
plh97 opened this issue Sep 24, 2020 · 0 comments
Open

[Redux] 简单实现 #164

plh97 opened this issue Sep 24, 2020 · 0 comments
Assignees
Labels
javaScript 关于js的一些事 react react项目 学习 如果不学习,那今天和昨天又有什么区别

Comments

@plh97
Copy link
Owner

plh97 commented Sep 24, 2020

视频解说: https://www.youtube.com/watch?v=QOUao86FPxg

实现步骤

  1. 发布订阅器实现 ✔️
  2. Reducer 实现 ✔️
  3. CombineReducer 实现 ✔️
  4. Middleware 实现 ✔️
  5. ApplyMiddleware 实现 [midd1, midd2] ✔️
  6. React-hooks + redux 实现 todo-list-filter UI MVC ✔️

代码

function CombineReducer(reducers) {
  return function combine(state, action) {
    const newState = {};
    Object.keys(reducers).forEach((key) => {
      newState[key] = reducers[key](state[key], action);
    });
    return newState;
  };
}
const CreateStore = (combination, initState, rewriteCreateStore) => {
  if (typeof initState === 'function') {
    return initState(CreateStore)(combination);
  }
  if (rewriteCreateStore) {
    return rewriteCreateStore(CreateStore)(combination, initState);
  }
  let state = {};
  const listeners = [];
  function subscript(cb) {
    listeners.push(cb);
    return function unsubscript() {
      listeners.splice(listeners.indexOf(cb), 1);
    };
  }
  function getState() {
    return state;
  }
  function dispatch(action) {
    state = combination(state, action);
    listeners.forEach((cb) => {
      cb();
    });
  }
  dispatch({ type: Symbol(1) });
  return {
    subscript,
    getState,
    dispatch,
  };
};

function ApplyMiddleware(middlewares) {
  return function rewriteCreateStoreFunc(oldCreateStore) {
    return function newCreateStore(reducer, initState) {
      const store = oldCreateStore(reducer, initState);
      let { dispatch } = store;
      const chains = middlewares.map((middleware) => middleware({ getState: store.getState }));
      chains.reverse().forEach((chain) => {
        dispatch = chain(dispatch);
      });
      store.dispatch = dispatch;
      return store;
    };
  };
}

export {
  CombineReducer,
  CreateStore,
  ApplyMiddleware,
};

Reference

redux原理全解 | 前端面试与进阶指南

@plh97 plh97 self-assigned this Sep 24, 2020
@plh97 plh97 added java Java CS Language react react项目 学习 如果不学习,那今天和昨天又有什么区别 javaScript 关于js的一些事 and removed java Java CS Language labels Sep 24, 2020
@plh97 plh97 changed the title redux 简化实现 [Redux] 简单实现 Oct 6, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
javaScript 关于js的一些事 react react项目 学习 如果不学习,那今天和昨天又有什么区别
Projects
None yet
Development

No branches or pull requests

1 participant