Anti Pattern: Accessing State in Reducer? How to handle interdependent reducers?

坚强是说给别人听的谎言 提交于 2019-12-11 07:48:47

问题


I've read in several places now that accessing state in action creators is an anti-pattern. Dan Abramov has said

In general accessing state in action creators is an anti-pattern and you should avoid this when possible.

I have recently found myself in the following situation. I have 2 reducers:

currentUser:

{ 
  currentUserId: 'abc'
}

allUsers

{ 
  byId: {
  {
   abc: {
         name: "John"
         age: 21
        }
   def: {
         name: "Dave"
         age: 51
        }
   ghi: {
         name: "Gunners"
         age: 98
        }
  }
},
  allIds : ['abc','def','ghi'] //this is a list; users have a certain order, that is preserved here
}

The byId /allIds structure I have also taken from Dan Abramov / Redux

Now say I want to dispatch the following action:

export const getNextActiveUser = () => {
  return {
    type: "NEXT_USER"
  };
};

Well, I would need to update currentUserId to def. But I can only get def if I find the position of abc in allIds and increment the index. Only then can I update my other reducer.

I don't understand how to do this without accessing state in my action creator. Any advice?

来源:https://stackoverflow.com/questions/57376470/anti-pattern-accessing-state-in-reducer-how-to-handle-interdependent-reducers

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