【问题标题】:Dispatch in react redux在 react redux 中调度
【发布时间】:2018-05-05 20:19:13
【问题描述】:

我是新来的反应和 redux xo 我的问题听起来很基础。

  1. 调度是什么意思?我指的是调度动作这个术语。
  2. 为什么我们需要 mapDispatchToProps 来存储 redux 上的操作?我们可以简单地导入一个动作并使用它。我有一个场景,我必须在安装组件时加载数据。

【问题讨论】:

  • 您可以阅读此答案 stackoverflow.com/questions/41670146/… dispatch 调度操作。这是触发状态更改的唯一方法。
  • @ShubhamKhatri 它仍然没有回答我的问题。
  • 您的第二个问题与第一个问题有关。您需要分派,因为这是触发状态更改的唯一方法,并且 mapDispatchToProps 不是必需的,您可以在导入操作后分派操作,如链接中的答案所解释的那样。也请阅读文档,它解释得很清楚redux.js.org/docs/api/Store.html#dispatch
  • 这个问题太宽泛了。您可能想先完成阅读:redux.js.org/docs/introduction

标签: reactjs redux react-redux


【解决方案1】:

@mariazahid mapDispatchToProps 会将操作绑定到您的组件,以便您可以将其传递给您的演示组件。这是一种通常在使用 Redux 和 React 时使用的模式。

您可以导入您的操作并直接调度该操作,但在大多数情况下使用容器 -> 组件模式。容器是动作和状态映射到的地方,该组件的唯一目标是将这些数据向下传递给用于呈现该数据的组件。

在团队中工作时,这是一种很容易采用的模式。无需从左右和中心导入操作,您只需了解容器以及它如何将所需的操作/数据传递给子级。

【讨论】:

    【解决方案2】:

    从实现的角度来看,dispatch 只是一种用于与您的 reducer 通信的方法

    假设您的操作看起来像这样

    function myAction() {
      return { type: 'MY_ACTION' }; 
    }
    

    您正在尝试与响应操作类型“MY_ACTION”的 reducer 通信

    在您的mapDispatchToProps 中,您通常会这样做;

    function mapDispatchToProps(dispatch) {
      return { actions: bindActionCreators(myActions, dispatch) }
    }
    

    实际上,您正在将您的操作包装(绑定)到调度方法;

    function bindActionCreators(actions, dispatch) {
      // this is a very trivial implementation of what bindActionCreators does
    
      let wrappedActions = {};
      Object.keys(actions).forEach(action => 
        // for every action, return a function that calls dispatch on the result of what your action returns
        return function(...args) {
          // remember here that dispatch is the only way you can communicate with the reducers and you're action's type will determine which reducer responds to return the new state
          return dispatch(actions[action](..args));
        }
      );
    }
    

    因此,这些“绑定”操作现在已分配给组件中的 props.actions

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-24
      • 2021-10-14
      • 2019-02-15
      • 2017-08-09
      相关资源
      最近更新 更多