const createStore=(reducer)=>{//创建仓库,传入管理员函数
let state;//state为undefined
let listeners=[];//监听函数数组
let subscribe=(listener)=>{//订阅函数:传入一个监听函数,当状态发生变化,会取消对应的监听函数(中间还有一步是让对应的监听函数执行,在dispatch中执行)
listeners.push(listener );
return ()=>{
listeners=listeners.filter(item=> item!==listener)
};
};
let dispatch=(action)=>{//派发动作
state=reducer(state,action)//传入老的state和action,返回新的state
listeners.forEach(item=>{ item()})//让所有的监听函数执行
};
dispatch({});//之所以action传个{},是为了用reducer里的初始状态覆盖掉redux里初始的state
let getState=()=> state;
return {
getState,//获取最新的状态
subscribe,//用来订阅状态变化事件,如渲染组建的事件
dispatch,//派发动作,来改变状态
};
};