【问题标题】:Redux - Removing entities from related stateRedux - 从相关状态中删除实体
【发布时间】: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_REQUESTDELETE_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


【解决方案1】:

与其使您的操作复杂化,不如在您的减速器中处理这个选项(如 cmets 中所建议的那样)。通过以下方式,您仍然可以使用 combineReducers 但拥有一个以 {foo,bar,bas} 为状态的组合减速器:

const fooBarBaz = combineReducers({
  foo:fooReducer,
  bar: barReducer,
  baz:bazReducer,
});
const combined = (state,action)=>{
  //handle foo remove success action, state is {foo,bar,baz}
}
export default function reducer(state,action){
  return combined(fooBarBaz(state,action),action)
}

【讨论】:

  • 这是可行的,我从未见过这样的例子,这是一种常见的方法吗?
  • @user3690467 即使您看不到太多,但在您的情况下可能更简单,事实是 combineReducers 只是创建了一个减速器函数 (state,action)=>newState 并且您可以拥有尽可能多的减速器.大多数示例在可以分离的切片中使用 combineReducers 拆分状态,您只需分离一些和(Foo、Bar 或 Baz),但需要某些操作才能获得 {Foo,Bar,Bas}
猜你喜欢
  • 2018-08-29
  • 2016-10-13
  • 2017-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多