/**
* createStore方法的实现方式
*/
const createStore = (reducer) => {
let state;
let listeners = [];
const getState = () => state;
const dispatch = (action) => {
state = reducer(state, action);
// 1、State 一旦有变化,Store 就会调用监听函数。但如下写法并未监控state的变化,怎样监控state的变化呢?
listeners.forEach(listener => listener());
};
const subscribe = (listener) => {
listeners.push(listener);
return () => {
listeners = listeners.filter(l => l !== listener);
}
};
// 2、这里为什么要调用一下dispatch呢?
dispatch({});
return { getState, dispatch, subscribe };
};