【发布时间】:2020-02-08 23:48:26
【问题描述】:
我有如下形式的redux状态,使用combineReducers分片管理:
interface AppState {
foos: Foo[];
bars: Bar[];
bazs: Baz[];
}
它们以下列方式相关:
一个Foo 有多个Bar。一个Bar 有多个Baz。它们的结构如下:
interface Foo {
id: string;
name: string;
}
interface Bar {
id: string;
name: string;
fooId: string;
}
interface Baz {
id: string;
name: string;
barId: string;
}
我为状态的每个部分设置了常规的 thunk/actions,即 DELETE_FOO_REQUEST、DELETE_FOO_FAILURE DELETE_FOO_SUCCESS 以及每个实体的其他 CRUD 选项。
我的 delete foo thunk 看起来像这样:
function deleteFoo(fooId) {
return async (dispatch, getState) => {
dispatch(deleteFooRequest());
await api.deleteFoo(fooId);
dispatch(deleteFooSuccess(fooId);
// omitted error handling for brevity
}
}
问题是:当我在我的 api/后端删除 Foo 时,它也会删除所有相关的 Bars 和 Bazs。现在在使用redux-thunk 约定时如何处理这个问题?
我是否要创建更多 DELETE_BARS_FOR_FOO 形式的操作并在同一个 thunk 中分派这些操作?还是我重复使用DELETE_BAR_SUCCESS 并循环使用它?
选项 A
function deleteFoo(fooId) {
return async (dispatch, getState) => {
dispatch(deleteFooRequest());
await api.deleteFoo(fooId);
const barIds: string[] = selectBarsForFoo(fooId);
dispatch(deleteFooSuccess(fooId);
dispatch(deleteBarsForFoo(fooId);
for (const barId of barIds) {
dispatch(deleteBazForBar(barId));
}
// omitted error handling for brevity
}
}
选项 B
function deleteFoo(fooId) {
return async (dispatch, getState) => {
dispatch(deleteFooRequest());
await api.deleteFoo(fooId);
const barIds: string[] = selectBarsForFoo(fooId);
dispatch(deleteFooSuccess(fooId);
for (const barId of barIds) {
dispatch(deleteBarSuccess(barId));
}
// followed by a similar loop for the bazs of each bar
// omitted error handling for brevity
}
}
在选项 B 的情况下,我正在重用一个在技术上意味着其他东西的动作。在这两个动作中,我都在一个循环中调度,这也会影响性能。但是我正在使用 react-redux 并且可以使用 batch() api,所以不用担心。
这是我在使用 redux-thunk 时仅有的两个选择,还是有更好/传统的方法来解决这个问题?
【问题讨论】:
-
deleteFooSuccess reducer中也可以删除相关的Foo数据。
-
数据没有嵌套,我使用的是 combineReducer,所以组件状态无法访问其他状态
-
我错过了,您仍然可以拥有多个 combine reducer,一个用于处理 Appstate,一个用于分别处理 Foo、Bar 和 Baz。
标签: reactjs redux react-redux redux-thunk