关于Redux
* 将数据和reducer合并在一起生产redux(store)对象
* 提供Provider将redux存到context里,以便随时可以调用store.dispatch
这两天有了更深入的一些了解,redux中最难理解的一部分是middleware部分
例如thunk
export default function thunkMiddleware({ dispatch, getState }) { return next => action => typeof action === 'function' ? action(dispatch, getState) : next(action); }
第一次看的时候,很难理解next的作用,后来结合applyMiddleware进行对比才比较清晰一些:
export default function applyMiddleware(...middlewares) { return (next) => (reducer, initialState) => { var store = next(reducer, initialState); var dispatch = store.dispatch; var chain = []; var middlewareAPI = { getState: store.getState, dispatch: (action) => dispatch(action) }; chain = middlewares.map(middleware => middleware(middlewareAPI)); dispatch = compose(...chain, store.dispatch); return { ...store, dispatch }; }; }
这里也有next,而next的作用是接收createStore从而进行store的初始化,用于后续的applyMiddleware
比较关键的有两点,一点是
middleware => middleware(middlewareAPI)
将middleware绑定上 getState和dispatch变量
另外一点是使用compose,不断的使用闭包将middleware绑定给下个middleware的next
最终将所有的middleware包裹在store.dispatch外面成为新的dispatch