'use strict';
import { createStore, applyMiddleware} from 'redux';
import thunkMiddleware from 'redux-thunk';
const createStoreWithMdware = applyMiddleware(
thunkMiddleware
)(createStore);
export default createStoreWithMdware;
第一眼看上去,我去。这面这一坨是什么东西?第一次我见的时候也模糊。
const createStoreWithMdware = applyMiddleware(
thunkMiddleware
)(createStore);
可以跳过,这里是总体分析,我们学习的createStore创建store,它可以接受reducer参数。因为要处理action发送请求的异步问题,因此引入了applyMiddleware,applyMiddleware是一个高阶函数,它将中间件装饰到了createStore函数上。
现在我们要解释为何有上面的写法,首先让我看看applyMiddleware的源码
function applyMiddleware() {
//1
for (var _len = arguments.length, middlewares = Array(_len), _key = 0; _key < _len; _key++) {
middlewares[_key] = arguments[_key];
}
//2
return function (createStore) { ************************
//3
return function (reducer, preloadedState, enhancer) { *******************
//4
var store = createStore(reducer, preloadedState, enhancer);
var _dispatch = store.dispatch;
var chain = [];
//5
var middlewareAPI = {
getState: store.getState,
dispatch: function dispatch(action) {
return _dispatch(action);
}
};
chain = middlewares.map(function (middleware) {
return middleware(middlewareAPI);
});
//6
_dispatch = _compose2['default'].apply(undefined, chain)(store.dispatch);
return _extends({}, store, {
dispatch: _dispatch
});
};
};
}
看到上面我➕ **************** 的2行了吗?
其实applyMiddleware返回了一个函数,并且这个函数内又嵌套了一个函数(嵌套函数)。因此,下面黄色线的位置就是执行了applyMiddleware返回的函数。此刻createStoreWithMdware这个变量保存一个函数,这个函数就是返回的第二层函数(即嵌套函数)
image.png如果理解了上面的话。那么接下来就好理解了。
const store = createStoreWithMdware(reducers);
ReactDom.render(
<Provider store={store}>
<Router history={history} routes={routes} />
</Provider>,
document.getElementById('container')
);
网友评论