【发布时间】:2017-10-03 07:35:02
【问题描述】:
虽然这是关于
applyMiddleware的实现,但我认为这是与传播运算符有关的问题的重复,因为心理问题的核心正是如此。
序言:
当涉及到事情发生的原因实际上并不清楚的时候,我不喜欢魔法。所以我在查看实际的 redux 实现。
有什么问题?
嗯,我在applyMiddleware的实现中看到了这一点:
import compose from './compose'
/**
* Creates a store enhancer that applies middleware to the dispatch method
* of the Redux store. This is handy for a variety of tasks, such as expressing
* asynchronous actions in a concise manner, or logging every action payload.
*
* See `redux-thunk` package as an example of the Redux middleware.
*
* Because middleware is potentially asynchronous, this should be the first
* store enhancer in the composition chain.
*
* Note that each middleware will be given the `dispatch` and `getState` functions
* as named arguments.
*
* @param {...Function} middlewares The middleware chain to be applied.
* @returns {Function} A store enhancer applying the middleware.
*/
export default function applyMiddleware(...middlewares) {
return (createStore) => (reducer, preloadedState, enhancer) => {
const store = createStore(reducer, preloadedState, enhancer)
let dispatch = store.dispatch
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
}
}
}
return {
...store,
dispatch
}
所以它实际上是在 store 对象的第一层散布了整个 store。但我们只是想应用中间件,并没有实际操作存储。
那么为什么不直接执行以下操作呢?
return {
store,
dispatch
}
在这个非常具体的实现中/在使用它的应用程序范围内,使用 store 而不是 ...store 会有什么副作用?
【问题讨论】:
标签: javascript redux react-redux middleware