javascript - 为什么 redux 在其 applyMiddleware 实现中执行 `{... store}` ?

标签 javascript redux react-redux middleware

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 的实现中看到了这一点:

applyMiddleware.js on github

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/

相关文章:

reactjs - 如何处理redux表单提交的数据

javascript - 是否可以使用一个变量值作为另一个变量名称的一部分?

reactjs - 如何在 React App State 中最好地存储 MQTT 消息的复杂对象?

reactjs - 使用 Redux 的类组件

javascript - 尝试做过滤器时如何正确构造 reducer ?

javascript - 在 redux 操作中查询 api 时出现无限循环

javascript - 如何更改此 React(Redux) 组件使其独立运行

javascript - Google Visualization - 发送二维数组,但不起作用

javascript - 自动复制隐藏文本

javascript - 可排序面板,从其中的某些元素中删除可拖动功能