react-redux的学习摘记

redux的api

applyMiddleware // 应用中间件
bindActionCreators // 将action转化为props
combineReducers: 将多个reducer合并为一个
compose //
createStore //创建store

react-redux的api

Provider:
connect: 
// 前两个最常用,后面几个不常用
connectAdvanced: (...)
createDispatchHook: (...)
createSelectorHook: (...)
createStoreHook: (...)
shallowEqual: (...)
useDispatch: (...)
useSelector: (...)
useStore: (...)
ReactReduxContext:
batch: (...)

store的方法

dispatch: ƒ ()
getState: ƒ f()
// dispatch和getState最为常用
liftedStore: {dispatch: ƒ, subscribe: ƒ, getState: ƒ, replaceReducer: ƒ, Symbol(observable): ƒ}
replaceReducer: ƒ (n)
subscribe: ƒ subscribe(listener)
Symbol(observable): ƒ ()

createStore的简单实现

const createStore = (reducer) => {
  let state;
  let listeners = [];

  const getState = () => state;
  // getState方法,获取全局state

  const dispatch = (action) => {
    // dispatch方法执行后,1.先运行reducer函数,得到新的state
    state = reducer(state, action);
    // 2. 再执行各个订阅函数,一般是render方法
    // 第1步和第2步顺序不能倒过来
    listeners.forEach(listener => listener());
  };

  const subscribe = (listener) => {
    // 订阅的时候,将订阅函数存到函数库中
    listeners.push(listener);
    // 返回一个新的方法取消订阅函数,如果运行该取消订阅函数,那么就会将该listener取消。
    return () => {
      listeners = listeners.filter(l => l !== listener);
    }
  };

  dispatch({}); //dispatch一个空的action,得到state的初始值,就是reducer中default的返回值

  return { getState, dispatch, subscribe };
};

你可能感兴趣的:(react-redux的学习摘记)