redux 派遣还原React

yr9zkbsy  于 2023-03-18  发布在  React
关注(0)|答案(3)|浏览(122)

我是新的React和redux xo我的问题将听起来基本。
1.调度是什么意思?我指的是调度一个动作。
1.为什么我们需要mapDispatchToProps来存储redux上的操作?我们可以简单地导入一个操作并使用它。我有一个场景,在这个场景中,当一个组件被挂载时,我必须加载数据。

cl25kdpy

cl25kdpy1#

@mariazahid mapDispatchToProps会将操作绑定到组件,以便您可以将其传递到表示组件。这是一种在使用Redux和React时通常使用的模式。
你可以导入你的动作并且仅仅分派动作,但是在大多数场景中使用容器-〉组件模式,容器是动作Map到的地方,状态和组件的唯一目标是将数据传递给用于呈现数据的组件。
在团队中工作时,这是一种很容易采用的模式。您只需了解容器以及它如何将所需的操作/数据传递给孩子,而不是从左到右或从中心导入操作。

jjhzyzn0

jjhzyzn02#

从实现的Angular 来看,dispatch只是用于与Reducer通信的方法
假设您的操作如下所示

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

您正在尝试与响应操作类型“MY_ACTION”的Reducer通信
mapDispatchToProps中,通常会执行以下操作;

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

实际上,您将操作 Package (绑定)到调度方法;

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

dhxwm5r4

dhxwm5r43#

const dispatch = (action) => {
  // execute the middleware chain, passing in the action
  const result = middlewareChain(action);

  // update the store with the new state returned by the middleware
  currentState = result;

  // trigger any subscribed listeners to update the UI
  for (const listener of listeners) {
    listener(currentState);
  }
}

此实现假定存在包含一个或多个中间件函数(如redux-thunk中间件)的middlewareChain数组。当使用操作调用dispatch时,它执行中间件链,并将操作作为参数传递。每个中间件函数都能够修改操作,或根据需要分派其他操作。
中间件链执行完毕后,dispatch会使用中间件返回的新状态更新存储的currentState,最后,dispatch会触发任何订阅的侦听器(如React组件)使用新状态更新UI。

相关问题