1. createStore
首先定义 createStore
用于创建一个 store:
const createStore = ({ reducers = {}, initialState }) => {
let state = initialState;
let listeners = [];
const getState = () => state;
const dispatch = ({ type, data }) => {
const reducer = reducers[type];
if (reducer) {
state = reducer(state, data);
}
listeners.forEach(listener => listener(state));
};
const subscribe = (listener) => {
listeners.push(listener);
return () => {
listeners = listeners.filter(l => l !== listener);
}
};
return {
getState,
dispatch,
subscribe
};
};
2. 使用
// 1. create store with initialState and reducers
const store = createStore({
initialState: [],
reducers: {
add: (state, data) => {
return [
...state,
data,
];
},
remove: (state, data) => {
return state.filter(c => c.id !== data.id);
}
},
});
// 2. subscribe listeners
const unSubscriber = store.subscribe(printState);
// 3. dispatch actions.
store.dispatch({ type: 'add', data: { id: 1, content: 'Article' } });
store.dispatch({ type: 'add', data: { id: 2, content: 'HaHa' } });
store.dispatch({ type: 'remove', data: { id: 2 } });
// 4. unsubscribe listener
unSubscriber();
// 5. print current state.
printState(store.getState());
网友评论