我正在探索有关redux中间件的更多信息。但坚持这一点,我不明白如何发送'可以在redux中间件中访问?是由于createStore功能吗? (在初始化时)
function createThunkMiddleware(extraArgument) {
console.log('createThunkMiddleware =================', extraArgument)
// console.log('dispatch =================', dispatch)
return ({ dispatch, getState }) => next => action => {
console.log('just above dispatch', dispatch)
if (typeof action === 'function') {
console.log('dispatch ======>',dispatch)
console.log('action =====>',action)
return action(dispatch, getState, extraArgument);
}
return next(action);
};
}
答案 0 :(得分:3)
关于咖喱功能和闭包的全部内容。您提供的中间件函数是通过compose调用的内部映射,而getstate和dispatch作为参数对象传递。 redux代码中的以下代码应该有用:https://github.com/reactjs/redux/blob/master/src/applyMiddleware.js#L30-L40
let chain = []
const middlewareAPI = {
getState: store.getState,
dispatch: (...args) => dispatch(...args)
}
chain = middlewares.map(middleware => middleware(middlewareAPI))
dispatch = compose(...chain)(store.dispatch)
return {
...store,
dispatch
}
正如你所看到的那样"链"是映射的函数数组,其中getstate和dispatch对象作为参数。希望这有助于您了解中间件的工作原理
答案 1 :(得分:2)
如果您快速浏览一下源代码,您会看到applyMiddleware
函数将中间件API注入每个中间件。
export default function applyMiddleware(...middlewares) {
return createStore => (...args) => {
const store = createStore(...args)
let dispatch = () => {
throw new Error(
`Dispatching while constructing your middleware is not allowed. ` +
`Other middleware would not be applied to this dispatch.`
)
}
let chain = []
const middlewareAPI = {
getState: store.getState,
dispatch: (...args) => dispatch(...args)
}
// Here is the interesting part where we pass in the dispatch
// and getState functions
chain = middlewares.map(middleware => middleware(middlewareAPI))
dispatch = compose(...chain)(store.dispatch)
return {
...store,
dispatch
}
}
}
这直接来自redux
源代码linke here!。我可以进入更多细节,但实际上我写了here,所以当我详细讨论这个问题时,请查看。我希望这有帮助,如果您有其他问题,请告诉我!