Although this is about the
applyMiddleware
implementation I accept this being a duplicate of the question referring to the spreading operator as the core of the mental issue is exactly that.
序言:
当事情发生的原因实际上并不清楚时,我不喜欢魔法。所以我正在研究实际的 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
}
所以它实际上是将整个商店分布在商店对象的第一层。但我们只是想应用中间件,而不是实际操作存储。
那么为什么不直接执行以下操作呢?
return {
store,
dispatch
}
在这个非常具体的实现中/在使用它的应用程序范围内,通过 ...store
进行 store
会产生什么副作用?
最佳答案
使用 store
而不是 ...store
会完全改变表达式的含义。
{store,dispatch}
含义与:{store: store,dispatch:dispatch}
而{...store,dispatch}
表示扩展/合并原始store
对象与新的dispatch
属性。
了解更多 here关于扩展语法。
关于javascript - 为什么 redux 在其 applyMiddleware 实现中执行 `{... store}` ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46539412/