简体   繁体   中英

How do I reset the state to its initial state?

I can't seem to reset the default state; how do I do that? I tried this but all it does is add state to state and calls it undefined.

const initialState = {
  name: null,
  coins: 0,
  image: null,
};

export default function reducer(state = initialState, action = {}) {
  switch (action.type) {
    case types.ADD_GROUP_COINS:
      return {
        ...state,
        coins: state.coins + action.coins
      };
    case types.DELETE_GROUP:
      return {
        state: undefined
      };
    default:
      return state;
  }
}

To reset the state to the initialState , simply return initialState , like this:

case types.DELETE_GROUP:
  return initialState;

Remember that in the reducer, the object that you return is the new state . You don't need to wrap it in another object, like this:

return {
    state: ...
}

That will give you a property called state in your state, which isn't at all what you need.

From the documentation :

The reducer is a pure function that takes the previous state and an action, and returns the next state.

It's easy to get confused about this, so be careful! Take a look at your default case if you're still not quite sure: you're returning the old state variable as the new state, not { state: state } which you are essentially doing with the current DELETE_GROUP handler.

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