Redux 基本实现 发表于 2017-06-15 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152function createStore(reducer) { let state, listener = [], getState, dispatch, subscribe; dispatch = action => { state = reducer(state, action) listener.forEach(item => item()) } dispatch({}) subscribe = fn => { listener = [...listener, fn] return () => { listener = listener.filter(item => item !== fn) } } getState = () => JSON.parse(JSON.stringify(state)) return {dispatch, getState, subscribe}}/** * combineReducers 合并reducers * @param reducers[Object] 接收一个对象 * @returns {function()} */function combineReducers(reducers) { return (state = {}, action) => { let obj = {} for (let key in reducers) { if(!reducers.hasOwnProperty(key)) continue; obj[key] = reducers[key](state[key], action) } return obj }}/** * bindActionCreators 合并actions返回使用dispatch包装的结果 * @param actions * @param dispatch * @returns {{}} */function bindActionCreators(actions,dispatch) { //将actions 包装成 mapDispatchToProps返回的对象 let obj={}; for(let key in actions){ if(!actions.hasOwnProperty(key)) continue; obj[key]=(...arg)=>{ dispatch(actions[key](...arg)) } } return obj;}