Redux:Reducer 需要其他 Reducer 的状态? [英] Redux: Reducer needs state of other 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 组件只显示当前选择的项目.即,根据 currently-selected-item-reducer
中的 id,它会找到要在 all-items reducer
中显示的正确项目.
I have a simple React app and a React component simply displays the currently selected item. I.e., based on the id in the currently-selected-item-reducer
, it find the correct item to display in the all-items reducer
.
问题:
假设当前选定的项目是 123
并且我想实现一个按钮,该按钮将始终转到数组中的下一个项目.现在我需要在 all-items-reducer
中找到项目 123
,获取它在该数组中的索引,然后增加它.然后我的 React 组件将完成剩下的工作.
Say the currently selected item is 123
and I want to go to implement a button which will always go the next item in the array. Now I need to find item 123
in the all-items-reducer
, get its index in that array, and then increment it. Then my React component will do the rest.
然而,这意味着我需要访问我的 current-item reducer
中的 all-items-reducer
数组.这怎么可能?还是我在这里误解了什么?
However, this means that I need to access the array of the all-items-reducer
in my current-item reducer
. How is this possible? Or am I misunderstanding something here?
PS:我不想在我的 currently-selected-item-reducer
中引入计数器,因为这将是冗余信息:理论上,我应该能够找到通过查看 all-items-reducer 数组
并执行 findIndex()
或类似的操作来确定当前选择的项目位置.
PS: I would prefer to not introduce a counter in my currently-selected-item-reducer
, since this would be redundant information: I should, in theory, be able to find the item position of the current selection by looking at the all-items-reducer array
and do a findIndex()
or something like that.
推荐答案
您可以采用以下几种方法:
There are a few approaches you can take:
- 合并两个reducer;有人可能会争辩说,状态的两个部分是如此相互关联,以至于一个 reducer 应该处理一切.
- 在reducer 之间复制一些数据(显然很浪费,但如果reducer 真的非常独立,可能需要一点冗余)
- 让你的组件层弄清楚下一个项目是什么,然后调度特定的 ID 来选择.
- 使用类似
redux-thunk
的中间件,它不仅可以让您调度多动作创建动作,还可以让您查询状态.
- Combine the two reducers; one could argue that the two segments of state are so interrelated that one reducer should take care of everything.
- Duplicate some data across reducers (obviously is wasteful, but if the reducers are truly very separate, a little redundancy might be warranted)
- Let your component layer figure out what the next item is and dispatch the specific ID to select.
- Use something like the
redux-thunk
middleware which lets you not-only dispatch a multi-action-creating action but also lets you query state.
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());
这篇关于Redux:Reducer 需要其他 Reducer 的状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!