手写applyMiddleware
middleware的本质,是一个调用后可以得到dispatch创建函数的函数
compose:函数组合,将一个数组中的函数进行组合,形成一个新的函数,该函数调用时,实际上是反向调用之前组合的函数
export default function (...funcs) {
if (funcs.length === 0) {
return args => args;
}
if (funcs.length === 1) {
return funcs[0];
}
return function (...args) {
let lastReturn = null;
for (let i = funcs.length - 1; i >= 0; i--) {
const func = funcs[i];
if (i === funcs.length - 1) {
lastReturn = func(...args);
} else {
lastReturn = func(lastReturn);
}
}
return lastReturn;
}
// return funcs.reduce((a, b) => (...args) => a(b(...args)));
}
import compose from './compose'
export default function (...middlewares) {
return function (createStore) { //给我创建仓库的函数
//下面的函数用于创建仓库
return function (reducer, defaultState) {
//创建仓库
const store = createStore(reducer, defaultState);
let dispatch = () => { throw new Error("目前还不能使用dispatch") };
const simpleStore = {
getState: store.getState,
dispatch: store.dispatch
}
//给dispatch赋值
//根据中间件数组,得到一个dispatch创建函数的数组
const dispatchProducers = middlewares.map(mid => mid(simpleStore));
dispatch = compose(...dispatchProducers)(store.dispatch);
return {
...store,
dispatch
}
}
}
}