gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 05:09:06 27 4
gpt4 key购买 nike

假设我有两个 reducer 。

Reducer No.1 : Currently-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 组件只显示当前选定的项目。即,根据 current-selected-item-reducer 中的 id,它会找到要显示在 all-items reducer 中的正确项目。

问题:

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

但是,这意味着我需要在我的current-item reducer 中访问all-items-reducer 的数组。这怎么可能?还是我误解了什么?

PS:我宁愿不在我的 current-selected-item-reducer 中引入计数器,因为这将是冗余信息:理论上,我应该能够找到通过查看 all-items-reducer 数组 并执行 findIndex() 或类似的操作来确定当前选择的项目位置。

最佳答案

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

  1. 合并两个 reducer ;有人可能会争辩说,状态的两个部分是如此相互关联,以至于一个 reducer 应该处理所有事情。
  2. 跨 reducer 复制一些数据(显然是浪费,但如果 reducer 确实非常独立,则可能需要一点冗余)
  3. 您的组件层找出下一项是什么,并分派(dispatch)特定 ID 以供选择。
  4. 使用类似于 redux-thunk 中间件的东西,它不仅可以让您分派(dispatch)一个创建多 Action 的 Action ,还可以让您查询状态。

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());

关于javascript - Redux:Reducer 需要其他 Reducer 的状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51642726/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com