Redux 的中间件是定义一个函数,对 dispatch 举行革新,在发出 action 与实行 reducer 之间增加其他功用。这是对 Redux 举行功用拓展的体式格局。
Redux 怎样支撑中间件?
applyMiddlewares()
export default function applyMiddleware(...middlewares) {
return (createStore) => (reducer, preloadedState, enhancer) => {
var store = createStore(reducer, preloadedState, enhancer);
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}
}
}
middleware => middleware(middlewareAPI)
每一个 middleware 将能接见 getState 与 dispatch,同时能够晓得该 middleware 为高阶函数,实行返回一个函数
compose()
dispatch = compose(...chain)(store.dispatch);
export default function compose(...funcs) {
if (funcs.length === 0) {
return arg => arg
}
if (funcs.length === 1) {
return funcs[0]
}
const last = funcs[funcs.length - 1]
const rest = funcs.slice(0, -1)
return (...args) => rest.reduceRight((composed, f) => f(composed), last(...args))
}
(composed, f) => f(composed)
即:middleware({getState, dispatch})(store.dispatch)
该函数为高阶函数,实行返回一个函数
剖析至此,一个 middleware 函数大抵为:
({getState, dispatch})=> (next) => (action) => {
// next 即 store.dispatch
//...在此拓展功用
action() // action, 这个action实行触发dispath??
}
Action 怎样与Dispatch联系起来?
action 经由过程 bindActionCreator 与 dispatch 联系起来
bindActionCreator()
function bindActionCreator(actionCreator, dispatch) {
return (...args) => dispatch(actionCreator(...args))
}
(...args) => dispatch(actionCreator(...args))
由 actionCreator 能够晓得 actionCreator 为高阶函数,实行返回一个函数
所以一个 action 的姿态应该为:
()=> () => {
type: "",
payload
}
举例:redux-thunk 中间件
源码:
function thunkMiddleware({ dispatch, getState }) {
return next => action =>
typeof action === 'function' ?
action(dispatch, getState) :
next(action);
}
action 怎样写?
funciton fetchSomething(){
return (dispatch, getState)=>{
fetch().then((res)=>{
disatch({
type: "FETCH_SOMETHING_DONE"
palyload
})
})
}
}