How to reset the state of a Redux store?

前端 未结 30 1913
陌清茗
陌清茗 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 06:48

    With Redux if have applied the following solution, which assumes I have set an initialState in all my reducers (e.g. { user: { name, email }}). In many components I check on these nested properties, so with this fix I prevent my renders methods are broken on coupled property conditions (e.g. if state.user.email, which will throw an error user is undefined if upper mentioned solutions).

    const appReducer = combineReducers({
      tabs,
      user
    })
    
    const initialState = appReducer({}, {})
    
    const rootReducer = (state, action) => {
      if (action.type === 'LOG_OUT') {
        state = initialState
      }
    
      return appReducer(state, action)
    }
    

提交回复
热议问题