<h1>我们都知道redux-thunk是处理异步的中间件,但是他是怎么做到的呢?</h1>
话不多说直接源代码:
~~
function createThunkMiddleware(extraArgument) {
return ({ dispatch, getState }) => next => action => { if (typeof action === 'function') { return action(dispatch, getState, extraArgument); } return next(action); }; } const thunk = createThunkMiddleware(); thunk.withExtraArgument = createThunkMiddleware; export default thunk;
~~
这已经是redux-thunk的源代码了。
默认情况下redux 只能派发(dispatch)一个对象(object)
``
dispatch({ type: GETUSER, data: username })
``
当我们使用redux-thunk中间件的时候,就可以派发一个function啦!
dispatch(function (dispatch) {
$.get('/api/users', function(users) {
dispatch({
type: GETUSER,
data: username,
});
}); });;
当然什么时候 派发一个object ,什么时候派发一个function也是看项目架构的啦!哪个用起方便就用哪个。