首页 > 解决方案 > 注销时如何重置redux store?

问题描述

我试图在注销时重置我的存储,但它似乎根本不起作用。

如您所见,我正在为我的商店使用 AsyncStorage,并尝试遵循这篇文章的答案。

这是我在商店文件夹中的 index.js

import thunk from 'redux-thunk';
import { createStore, compose, applyMiddleware } from 'redux';
import { AsyncStorage } from 'react-native';
import { persistStore, autoRehydrate } from 'redux-persist';
import rootReducer from '../reducers';

var defaultState = {};

export function configureStore(initialState = defaultState) {
  var store = createStore(rootReducer, initialState, compose(
    applyMiddleware(thunk),
    autoRehydrate(),
  ));
  persistStore(store, { storage: AsyncStorage });
  return store;
}

这是我在 reducers 文件夹中的 index.js

import { combineReducers } from 'redux';
import { reducer as formReducer } from 'redux-form';
import { AsyncStorage } from 'react-native';

import authReducer from './authReducer';
import alertsReducer from './alertsReducer';
import jobsReducer from './jobsReducer';
import userDataReducer from './userDataReducer';

const appReducer = combineReducers({
  form: formReducer,
  auth: authReducer,
  alerts: alertsReducer,
  jobs: jobsReducer,
  userData: userDataReducer
})

const rootReducer = ( state, action ) => {
  if(action.type === 'UNAUTH_USER') {
    Object.keys(state).forEach(key => {
      AsyncStorage.removeItem(`persist:${key}`);
      console.log(state)
    });
  }
  return appReducer(state, action)
}

export default rootReducer

标签: reduxreact-redux

解决方案


On Initial load of our application the reducer state is fresh.

We Can copy this initial default state and use it to assign to our reducer again on logging out, the way we can achieve this could be as follows.

Step 1: call an action on the application load that will copy reducer's initial state as the defaultState

Step 2: While logging out of the application we can simply reAssign the default state and it should work as new.

App root Component

  componentDidMount() {   
    dispatch(ON_APP_LOAD)
  }

App Reducer

const appReducer = combineReducers({
  user: userStatusReducer,     
  analysis: analysisReducer,
  incentives: incentivesReducer
});

let defaultState = null;
export default (state, action) => {
  switch (action.type) {
    case **ON_APP_LOAD**:
      // will be assigned or called only once 
      defaultState = defaultState || state;
      break;
    case **RESET_STATE**:
      // detaching the reference on reset
      state = _.deepClone(defaultState);
      return state;
    default:
      break;
  }
  return appReducer(state, action);
};

On Logout calling the action for resetting state

function* logoutUser(action) {
  // on logout success 
  dispatch("RESET_STATE")
}

推荐阅读