redux实现

70 阅读1分钟

crateStore

内部定义一个currentState,用dispatch传进来的action来执行reducer获取到state(初始化和更新都用),订阅的时候获取传进来的函数并且存进全局的数组里,一旦执行dispatch就循环数组挨个执行订阅的函数,subscribe返回的时候就从数组中剔除。

export default function createStore(reducer) {
    const listeners = []
    //初始化state
    let currentState
  function getState() {
    return currentState
  }
  function dispatch(action) {
    currentState = reducer(currentState,action)
    //更新的时候执行listener
    listeners.forEach(i => i())
  }
  function subscribe(listener) {
    listeners.push(listener)
    return () => {
        const index = listeners.indexOf(listener)
        listeners.splice(index,1)
    }
  }

  //createStore的时候执行一会dispatch获取reuce的state
  let data = new Date()
  dispatch({type:data})
  return {
    getState,
    dispatch,
    subscribe,
  };
}