Redux:Reducer 需要其他 Reducer 的状态?

IT技术 javascript reactjs redux react-redux flux
2021-04-25 19:53:16

假设我有两个减速器。

Reducer No.1 : Current-Selected-Item-Reducer

state = {currentlySelectedItemId: 123}

Reducer No.2 : All-Items-Reducer

state = [{ id: 123, name: "John"}, {id: 231, name: "Jill"}, {id: 411, name: "Alf"}]

我有一个简单的 React 应用程序,一个 React 组件只是显示当前选择的项目。即,根据 中的 id currently-selected-item-reducer,它找到要在 中显示的正确项目all-items reducer

问题:

假设当前选定的项目是123,我想实现一个按钮,该按钮将始终转到数组中的下一个项目。现在我需要在 中找到项目123all-items-reducer在该数组中获取它的索引,然后增加它。然后我的 React 组件将完成剩下的工作。

但是,这意味着我需要访问all-items-reducer我的current-item reducer. 这怎么可能?或者我在这里误解了什么?

PS:我不想在我的 中引入计数器currently-selected-item-reducer,因为这将是多余的信息:理论上,我应该能够通过查看all-items-reducer array和执行 afindIndex()或类似的操作来找到当前选择的项目位置

1个回答

您可以采用以下几种方法:

  1. 结合两个减速器;有人可能会争辩说,状态的两个部分是如此相互关联,以至于一个 reducer 应该处理一切。
  2. 跨减速器复制一些数据(显然是浪费,但如果减速器真的非常独立,可能需要一点冗余)
  3. 你的组件层弄清楚下一个项目是什么,并调度特定的 ID 来选择。
  4. 使用redux-thunk中间件之类的东西,它不仅可以让您调度多动作创建动作,还可以让您查询状态。

redux-thunk方法示例

function gotoNextItem() {
  return (dispatch, getState) => {
    const { current, items } = getState(); // or whatever the reducers are called
    const index = items.findIndex(item => item.id === current.currentlySelectedItemId);
    const newIndex = (index + 1) % items.length;
    const newItem = items[newIndex];

    dispatch({ type: 'SELECT_ITEM', payload: { item: newItem } });
  };
}

store.dispatch(gotoNextItem());