Simulate Redux from simple to complex.
从零编写一个功能完整的Redux,包括combineReducers、applyMiddleware和bindActionCreators的实现等。
Create a simple store that can: get state/subscribe/change state.
Limit change by dispatching actions.
Combine reducers
Init state by reducer and trigger in createStore.
Logger middleware and exception middleware.
- Place middlewares in a seperate folder and be more extensible.
- Use applyMiddleware to combine the array of middlewares.
Other improvements:
- Unsubscribe store
- Use simple store in middlewares
const simpleStore = { getState: store.getState };
const chain = middlewares.map(middleware => middleware(simpleStore));
- Support to omit initState
// old
const store = createStore(reducer, {}, rewriteCreateStoreFunc);
// new
const store = createStore(reducer, rewriteCreateStoreFunc);
// change code
function craeteStore(reducer, initState, rewriteCreateStoreFunc){
if (typeof initState === 'function'){
rewriteCreateStoreFunc = initState;
initState = undefined;
}
...
}
- Add replaceReducer in createStore to support lazy load of reducer.
- Add bindActionCreators to simplify dispatching actions.