简体   繁体   中英

Redux sharing actions between components

I'm building a mobile app with react-native and redux, I'm organizing my project structure by features in this way:

Component1/
---Component1Actions.js
---Component1Reducer.js
---...
Component2/
---Component2Actions.js
---Component2Reducer.js
---...

In my opinion this kind of project structure is amazing for many reasons, first of all for its great scalability. Only problem I have come across so far is when 2 different components have to dispatch the same actions (such as a simple text change in a textbox).
It wouldn't make sense to rewrite the exact same action in 2 different files and I also know that importing an action from one component to another component is really a bad practice. I thought about keeping these kind of "shareable" actions in a global module and then import them in the various components but I'm not sure if it is a good practice.
I would like to know the best way to handle this kind of situations.
Thanks in advance.

You can handle the same "ACTION_TYPE" in multiple reducers.

... actions are by design global. They are not meant to be tied to a particular reducer (Dan Abramov)

You could handle an "LOGOUT" action in all your reducers, which would just return the initial state.. and set the application to defaults

for example..

const postReducer = (state = initial, action) => {
  swtich(action.type) {
  ...
  case "LOGOUT": 
    return initial 
  default: 
    return state
  }
}
  1. Define it in common reducers.js, actions.js.
  2. In compose pass it to REACT component connect(mapStateToProps, {commonAction, ...actions})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM