我试图在注销时重置存储,但似乎根本无法正常工作。
如您所见,我正在为商店使用AsyncStorage,我尝试遵循this帖子中的回答。
这是商店文件夹中的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
答案 0 :(得分:0)
以下解决方案对我有用。
首先在我们应用程序的 初始化 中,减速器状态为 新鲜 和 新 和默认的 InitialState 。
我们必须添加一项操作,以调用APP初始加载以保持 默认状态 。
退出应用程序时,我们可以简单地 reAssign 默认状态 ,而reducer的工作原理与 新 。
主APP容器
componentDidMount() {
this.props.persistReducerState();
}
主APP还原器
const appReducer = combineReducers({
user: userStatusReducer,
analysis: analysisReducer,
incentives: incentivesReducer
});
let defaultState = null;
export default (state, action) => {
switch (action.type) {
case appActions.ON_APP_LOAD:
defaultState = defaultState || state;
break;
case userLoginActions.USER_LOGOUT:
state = defaultState;
return state;
default:
break;
}
return appReducer(state, action);
};
在注销呼叫时重置状态
function* logoutUser(action) {
try {
const response = yield call(UserLoginService.logout);
yield put(LoginActions.logoutSuccess());
} catch (error) {
toast.error(error.message, {
position: toast.POSITION.TOP_RIGHT
});
}
}
希望这可以解决您的问题!
答案 1 :(得分:0)
我假设您有一个js文件,其中所有的reducer都组合在一起,因此您拥有:
c++11
,并在您需要定义存储的索引文件中
const allReducers = combineReducers({
reducer: nameOfReducer
});
const rootReducer = (state, action) => {
switch (action.type) {
case CLEAR_ALL_REDUCERS_DATA:
return state = undefined;
default:
return allReducers(state, action)
}
};
export default rootReducer;
,然后在注销时直接调用它:
const store = createStore(rootReducer,
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
);
其中clearAllStoreData是您的操作文件中定义的操作:
dispatch(clearAllStoreData());