[英]Redux: Reducer needs state of other Reducer?
Say I have two reducers. 说我有两个减速器。
Reducer No.1 : Currently-Selected-Item-Reducer 减速机No.1:当前选择项目减速机
state = {currentlySelectedItemId: 123}
Reducer No.2 : All-Items-Reducer 减速机2号:All-Items-Reducer
state = [{ id: 123, name: "John"}, {id: 231, name: "Jill"}, {id: 411, name: "Alf"}]
I have a simple React app and a React component simply displays the currently selected item. 我有一个简单的React应用程序和一个React组件只显示当前选定的项目。 Ie, based on the id in the
currently-selected-item-reducer
, it find the correct item to display in the all-items reducer
. 即,基于
currently-selected-item-reducer
的id,它找到要在all-items reducer
显示的正确项目。
Problem: 问题:
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. 假设当前选择的项目是
123
,我想要实现一个按钮,它始终是数组中的下一个项目。 Now I need to find item 123
in the all-items-reducer
, get its index in that array, and then increment it. 现在我需要在
all-items-reducer
找到item 123
,在该数组中获取它的索引,然后递增它。 Then my React component will do the rest. 然后我的React组件将完成剩下的工作。
However, this means that I need to access the array of the all-items-reducer
in my current-item reducer
. 但是,这意味着我需要在
current-item reducer
访问all-items-reducer
的数组。 How is this possible? 这怎么可能? Or am I misunderstanding something here?
或者我在这里误解了什么?
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. PS:我宁愿不在我
currently-selected-item-reducer
引入一个计数器,因为这将是多余的信息:理论上,我应该能够通过查看all-items-reducer array
找到当前选择的项目位置 - all-items-reducer array
并执行findIndex()
或类似的操作。
There are a few approaches you can take: 您可以采取以下几种方法:
redux-thunk
middleware which lets you not-only dispatch a multi-action-creating action but also lets you query state. redux-thunk
中间件这样的东西,它不仅可以调度多动作创建动作,还可以让你查询状态。 Sample of redux-thunk
approach: 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());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.