How to reset the state of a Redux store?

前端 未结 30 1887
陌清茗
陌清茗 2020-11-22 06:20

I am using Redux for state management.
How do I reset the store to its initial state?

For example, let’s say I have two user accounts (u1 and

30条回答
  •  隐瞒了意图╮
    2020-11-22 06:37

    My take to keep Redux from referencing to the same variable of the initial state:

    // write the default state as a function
    const defaultOptionsState = () => ({
      option1: '',
      option2: 42,
    });
    
    const initialState = {
      options: defaultOptionsState() // invoke it in your initial state
    };
    
    export default (state = initialState, action) => {
    
      switch (action.type) {
    
        case RESET_OPTIONS:
        return {
          ...state,
          options: defaultOptionsState() // invoke the default function to reset this part of the state
        };
    
        default:
        return state;
      }
    };
    

提交回复
热议问题