使用configureStore和'@ reduxjs / toolkit'时,如何在注销后将存储重置为初始状态

时间:2019-11-27 00:04:15

标签: redux

我已经看到了注销后清除/重置存储的解决方案,但不了解如何通过以下方式来建立相同的功能来设置redux存储。

Store.js:


import { configureStore, getDefaultMiddleware } from '@reduxjs/toolkit'
import authReducer from './ducks/authentication'
import snackbar from './ducks/snackbar'
import sidebar from './ducks/sidebar'
import global from './ducks/global'
import quickView from './ducks/quickView'
import profileView from './ducks/profileView'

const store = configureStore({
  reducer: {
    auth: authReducer,
    snackbar,
    sidebar,
    global,
    quickView,
    profileView,
  },
  middleware: [...getDefaultMiddleware()],
})

export default store



这是使用@ reduxjs / toolkit中的createAction和createReducer实现所有化简器的方式。

snackbar.js:


import { createAction, createReducer } from '@reduxjs/toolkit'

export const handleSnackbar = createAction('snackbar/handleSnackbar')

export const openSnackBar = (
  verticalPosition,
  horizontalPosition,
  message,
  messageType,
  autoHideDuration = 10000
) => {
  return async dispatch => {
    dispatch(
      handleSnackbar({
        verticalPosition,
        horizontalPosition,
        message,
        autoHideDuration,
        messageType,
        isOpen: true,
      })
    )
  }
}

export const closeSnackbar = () => {
  return dispatch => {
    dispatch(handleSnackbar({ isOpen: false }))
  }
}

const initialState = {
  verticalPosition: 'bottom',
  horizontalPosition: 'center',
  message: '',
  autoHideDuration: 6000,
  isOpen: false,
  messageType: 'success',
}

export default createReducer(initialState, {
  [handleSnackbar]: (state, action) => {
    const {
      isOpen,
      verticalPosition,
      horizontalPosition,
      message,
      autoHideDuration,
      messageType,
    } = action.payload
    state.isOpen = isOpen
    state.verticalPosition = verticalPosition
    state.horizontalPosition = horizontalPosition
    state.message = message
    state.autoHideDuration = autoHideDuration
    state.messageType = messageType
  },
})



3 个答案:

答案 0 :(得分:6)

根据Dan Abramov's answer,创建一个 root reducer ,它将把 action 委派给您的主要或组合的reducer 。而且,每当根减速器收到 reset 类型的操作时,它都会重置状态。

示例:

const combinedReducer = combineReducers({
  first: firstReducer,
  second: secondReducer,
  // ... all your app's reducers
})

const rootReducer = (state, action) => {
  if (action.type === 'RESET') {
    state = undefined
  }
  return combinedReducer(state, action)
}

因此,如果您为商店配置了@reduxjs/toolkit's configureStore,则可能看起来像这样:

import { configureStore } from '@reduxjs/toolkit';
import counterReducer from '../features/counter/counterSlice';

export default configureStore({
  reducer: {
    counter: counterReducer,
    // ... more reducers
  },
});

其中configureStore的第一个参数reducer接受函数(被视为根减速器)或<{> 3的 object }}减速器,可使用slice在内部转换为 root reducer

因此,现在,我们可以通过自己创建并传递根缩减器,而不必传递切片缩减器的对象(如上所示),这是我们可以做到的:

const combinedReducer = combineReducers({
  counter: counterReducer,
  // ... more reducers
});

现在,让我们创建一个根减速器,在需要时执行我们的重置工作:

const rootReducer = (state, action) => {
  if (action.type === 'counter/logout') { // check for action type 
    state = undefined;
  }
  return combinedReducer(state, action);
};

export default configureStore({
  reducer: rootReducer,
  middleware: [...getDefaultMiddleware()]
});

这里是combineReducers

答案 1 :(得分:1)

我想扩展Ajeet的答案,以便那些希望在Redux商店中拥有完整类型安全性的人可以使用它。

主要区别在于您需要声明in the RTK docs类型的RootState类型

const combinedReducer = combineReducers({
  counter: counterReducer
});

export type RootState = ReturnType<typeof combinedReducer>;

然后在执行logout函数的rootReducer中,您想通过给state参数赋予RootState类型,以及{ {1}}参数action

难题的最后一部分是将您的状态设置为AnyAction类型而不是RootState的空对象。

undefined

我在CodeSandbox上添加了Ajeet的答案,添加了必需的类型,您可以here进行查看。

答案 2 :(得分:0)

带有两个减速器的简化示例:

// actions and reducer for state.first
const resetFirst = () => ({ type: 'FIRST/RESET' });

const firstReducer = (state = initialState, action) => {
    switch (action.type) {
        // other action types here

        case 'FIRST/RESET':
            return initialState;

        default:
            return state;
    }
};


// actions and reducer for state.second
const resetSecond = () => ({ type: 'SECOND/RESET' });

const secondReducer = (state = initialState, action) => {
    switch (action.type) {
        // other action types here

        case 'SECOND/RESET':
            return initialState;

        default:
            return state;
    }
};


const rootReducer = combineReducers({
    first: firstReducer,
    second: secondReducer
});

// thunk action to do global logout
const logout = () => (dispatch) => {
    // do other logout stuff here, for example logging out user with backend, etc..

    dispatch(resetFirst());
    dispatch(resetSecond());
    // Let every one of your reducers reset here.
};