我正在使用Redux进行状态管理。 如何将存储重置为初始状态?

例如,假设我有两个用户帐户(u1和u2)。 想象下面的一系列事件:

用户u1登录到应用程序并做了一些事情,所以我们在存储中缓存一些数据。 用户u1退出。 用户u2无需刷新浏览器即可登录应用。

此时,缓存的数据将与u1关联,我想清理它。

当第一个用户注销时,如何将Redux存储重置为初始状态?


当前回答

只需将注销链接清除会话并刷新页面。您的商店不需要额外的代码。当您想要完全重置状态时,页面刷新是一种简单且易于重复的处理方法。

其他回答

如果你想重置一个减速机

例如

const initialState = { isLogged:假 } //这将是你的行动 export const resetReducer = () => { 返回{ 类型:“重置” } } 导出默认值(state = initialState, { 类型, 有效载荷 }) => { 开关(类型){ //你的行动会报应到她头上 例“重置”: 返回{ initialState… } } } //从你的前端 调度(resetReducer ())

 const reducer = (state = initialState, { type, payload }) => {

   switch (type) {
      case RESET_STORE: {
        state = initialState
      }
        break
   }

   return state
 }

你也可以触发一个动作,由所有或部分还原器处理,你想重置到初始存储。一个动作可以触发你整个状态的重置,或者只是适合你的一部分。我相信这是最简单、最可控的方法。

这种方法非常正确:销毁任何特定状态“NAME”以忽略并保留其他状态。

const rootReducer = (state, action) => {
    if (action.type === 'USER_LOGOUT') {
        state.NAME = undefined
    }
    return appReducer(state, action)
}

在服务器中,有一个变量:global。isSsr = true 在每个reducer中,我都有一个const: initialState 要重置存储中的数据,我对每个Reducer执行以下操作:

appReducer.js的例子:

 const initialState = {
    auth: {},
    theme: {},
    sidebar: {},
    lsFanpage: {},
    lsChatApp: {},
    appSelected: {},
};

export default function (state = initialState, action) {
    if (typeof isSsr!=="undefined" && isSsr) { //<== using global.isSsr = true
        state = {...initialState};//<= important "will reset the data every time there is a request from the client to the server"
    }
    switch (action.type) {
        //...other code case here
        default: {
            return state;
        }
    }
}

最后在服务器的路由器上:

router.get('*', (req, res) => {
        store.dispatch({type:'reset-all-blabla'});//<= unlike any action.type // i use Math.random()
        // code ....render ssr here
});

对我来说,一个快速而简单的选择是使用还原复位。这是简单的,也有一些高级选项,为较大的应用程序。

在创建存储区中设置

import reduxReset from 'redux-reset'
// ...
const enHanceCreateStore = compose(
    applyMiddleware(...),
    reduxReset()  // Will use 'RESET' as default action.type to trigger reset
)(createStore)
const store = enHanceCreateStore(reducers)

在注销函数中调度您的“重置”

store.dispatch({
    type: 'RESET'
})