redux - 注销时如何重置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
解决方案
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")
}
推荐阅读
- c++ - C ++ for循环迭代更改整数向量值
- java - 尝试将数组列表与方法和构造函数一起使用。这可以优化吗?
- nltk - 用于非英语语言的基于 Python 的标记器
- java - Java 9+ 项目可以在 Java 8 中使用单独的源模块吗?
- c++ - 有没有办法在运行时分析 MPI 应用程序?- 在运行时使用 MPI 调用所花费的时间
- python - 如何执行代数,例如 apple + apple = 2 apple?
- elasticsearch - 确定哪些点位于 Kibana 上的弹性地图服务边界内
- laravel - 如何将接受文件限制和文件大小限制到 DropzoneJS
- r - 在 R 中并排创建多组直方图
- boost - 运行测试时找不到 boost_filesystem DLL