简体   繁体   中英

Update redux state object property

How do I update the property of an object in redux and preserve the rest of the object..

const appReducer = (state = initialState, action) => {
  switch (action.type) {
    case 'LOGIN_SUCCESS':
      return Object.assign({}, state, {
        user: { loggedIn: true, level: 'default' },
      });

    case 'UPDATE_PACKAGE': {
      // add a new value for the user.level which would be in action.level
      return { ...state, level: action.level };
    }

    default:
      return state;
  }
};

So I would expect the UPDATE_PACKAGE to change the contents of the redux store level property... but its unchanged...

So it seems like you're setting level on the root state instead of the user object.

This should fix it:

 case "UPDATE_PACKAGE": {
    return { ...state, user: { ...state.user, level: action.level } };
  }

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