【问题标题】:Redux react native: how to properly call multiple actions from different reducersRedux react native:如何正确调用来自不同reducer的多个动作
【发布时间】:2020-10-23 16:01:34
【问题描述】:

在我的 react native / redux 应用程序中,我想调度多个操作。

我在我的应用中处理一个元素列表。使用一个减速器,我将集合维护为 {CollectionId : [ElementId1, ElementId2, ElementId3] 的字典。在另一个减速器中,我维护了一个元素字典 {ElementId : {ElementName, ElementData, ...}}。这样数据就尽可能地标准化了。

现在,如果我想从特定 collectionId 中删除所有元素,我该如何调度以下两个操作:

batch(() => {
    dispatch(deleteCollection(collectionId)) // removes the collection from the first reducer dictionary
    dispatch(deleteElements(Array<ElementIds>)) // removes all Elements 
}),

但是我事先不知道数组,我只能访问collectionId。就像第一次调度应该返回元素 ID,这样我就知道在我的第二个减速器中必须进一步删除什么。

我的问题是:是否可以从 reducer 操作中返回一些值?我可以从我的第一个动作中调用我的第二个动作吗?我是否应该在减速器之外编写所有逻辑并且只使用减速器作为修改状态的一种方式,但计算如何从组件或其他东西中修改它?

【问题讨论】:

  • 必须是两个动作吗?为什么不只使用一个操作DELETE_COLLECTION 来删除集合并删除该集合的元素?我的意思是,是否存在需要删除集合并保留其元素的情况?

标签: reactjs redux action native dispatch


【解决方案1】:

首先您需要获取arrayOfElementIds。此外,您需要先删除Elements,然后再删除集合。

选项 1 - 假设 deleteElementsdeleteCollection 是异步的

// option 1 - assuming `deleteElements` and `deleteCollection` are asynchronous
const batch = () => (dispatch) => {
  dispatch(deleteElements(collectionId)); // removes all Elements
};

const deleteElements = (collectionId) => async (thunk) => {
  // make api call and delete
  const arrayOfElementIds = await getCollection(collectionId);
  await apiService.post("/url", arrayOfElementIds);
  dispatch(deleteCollection(collectionId)); // removes the collection from the first reducer dictionary
};

const getCollection = (collectionId) => { // write a little helper to get the array of ids
  // make an api call or dispatch an action or something like that and obtain array of element Ids
  return new Promise((res, rej) => {
    res(["array of ids..."]);
  });
};

选项 2 - 从存储中获取 arrayOfElementIds

// option 2 - get the arrayOfElementIds from the store using useSelector or mapStateToProps
const batch = () => {
  const arrayOfElementIds = useSelector(
    // get the arrayOfElementIds from the store
    (state) => state.ElementId.arrayOfElementIds
  );
  dispatch(deleteElements(arrayOfElementIds)); // removes all Elements
  dispatch(deleteCollection(collectionId)); // removes the collection from the first reducer dictionary
};

【讨论】:

  • 我喜欢这些想法,它们显然适用于删除之类的东西,对吧。但是现在,如果我还想实现像 RemoveDuplicates() 这样的东西,它也无济于事。如果我想删除重复项,我需要找到重复的元素,获取它们的 Id,删除它们,然后将这些 Ids 传递给集合减速器并从那里删除这些 Ids
猜你喜欢
  • 2018-10-16
  • 1970-01-01
  • 2015-12-28
  • 2017-12-20
  • 2021-10-06
  • 2017-08-02
  • 2018-02-13
  • 1970-01-01
  • 2017-01-30
相关资源
最近更新 更多