简体   繁体   中英

How to organise application state in redux store?

Imagine i had three main parts in my react application whose state is managed entirely by redux (no local state). Login , Register and View Profile :

My understanding is that the initial state would look like so:

const initialState = {
  login: {},
  register: {},
  profile: {},
  appUI: {
    menuToggled: false
  }
};


export function mainReducer(state = initialState, action) {
...

Then in my container component i would pull the relevant part of state using react-redux connect() :

function select(state) {
  return {
    state: state.login
  };
}

export default connect(select)(Login);

So when user types in username,password ..etc in the presentational component of login, the global state would be updated (using actions) and would end up looking like so:

{
  login: {
    username: "foo",
    password: "bar"
  },
  register: {},
  profile: {},
  app: {
    menuToggled: false
  }
};

Is this a valid approach? By valid i mean the way in which i am organising the state of my application, so if there were more "section" to the application as its growing (think crud) i would have greater number fields in the redux. I am new to react and redux and want to avoid any anti-patterns.

This is definitely not an anti-pattern. The entire purpose of mapStateToProps - the first parameter in connect - is to extract the part of the application state, that the component needs.

The one thing that concerns me though is that your container component depends on something like login credentials. Also, I do not know how you have structured your reducer, but I would recommend using the combineReducers function from redux .

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