reactjs - Redux react native:如何正确调用来自不同reducer的多个动作
问题描述
在我的 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 操作中返回一些值?我可以从我的第一个动作中调用我的第二个动作吗?我是否应该在减速器之外编写所有逻辑并且只使用减速器作为修改状态的一种方式,但计算如何从组件或其他东西中修改它?
解决方案
首先你需要得到arrayOfElementIds
. 您还需要删除第Elements
一个,然后是集合。
选项 1 - 假设deleteElements
并且deleteCollection
是异步的
// 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
};
推荐阅读
- macos - 在 MacOSX 上使用 gnuplot 5.2.8 出现文本问题
- html - CSS悬停过渡,从中心开始的宽度
- swift - Swift Mapkit, How to add tap gesture in custom annotation?
- python - 如何使用 Google colab 将文件下载到 Google Drive?
- scheduled-tasks - Schedule script to attach CSV file report to a data source in servicenow
- xml - XSD基本类型限制有什么问题
- java - 分离实体传递到持久 JPA Spring 引导保存
- sql - 从选择中的选择中删除空值
- node.js - npm 中的 node-cron 和 cron 模块是否相同?
- linux - 从wget下载时如何更改文件名?