模拟实现
2024年02月26日
一、Redux
function createStore(reducer, preloadState) {
let state = initialState;
let listeners = [];
function getState() {
return state;
}
function dispatch(action) {
state = reducer(state, action);
listeners.forEach((listener) => {
listener();
});
}
function subscribe(listener) {
listener.push(listener);
return () => {
listeners = listeners.filter((l) => l !== listener);
};
}
dispatch({ type: "DEFAULT" });
return {
getState,
dispatch,
subscribe,
};
}
export default createStore;