Redux: Reducer needs state of other Reducer?

為{幸葍}努か 提交于 2019-12-03 08:56:24

There are a few approaches you can take:

  1. Combine the two reducers; one could argue that the two segments of state are so interrelated that one reducer should take care of everything.
  2. Duplicate some data across reducers (obviously is wasteful, but if the reducers are truly very separate, a little redundancy might be warranted)
  3. Let your component layer figure out what the next item is and dispatch the specific ID to select.
  4. Use something like the redux-thunk middleware which lets you not-only dispatch a multi-action-creating action but also lets you query state.

Sample of redux-thunk approach:

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());
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!