我正在使用redux-persist和异步存储将数据持久保存在我的react-native-application中。
这是我的redux存储的配置
import AsyncStorage from '@react-native-community/async-storage';
import {applyMiddleware, createStore} from 'redux';
import {composeWithDevTools} from 'redux-devtools-extension';
import {persistReducer, persistStore} from 'redux-persist';
import createSagaMiddleware from 'redux-saga';
import rootReducer from '../reducers';
import rootSaga from '../sagas';
const sagaMiddleware = createSagaMiddleware();
// Middleware: Redux Persist Config
const persistConfig = {
// Root
key: 'root',
// Storage Method (React Native)
storage: AsyncStorage,
// Whitelist (Save Specific Reducers)
whitelist: ['authReducer',],
// Blacklist (Don't Save Specific Reducers)
blacklist: [''],
};
// Middleware: Redux Persist Persisted Reducer
const persistedReducer = persistReducer(persistConfig, rootReducer);
// Redux: Store
const store = createStore(
persistedReducer,
composeWithDevTools(applyMiddleware(sagaMiddleware)),
);
sagaMiddleware.run(rootSaga);
// Middleware: Redux Persist Persister
let persistor = persistStore(store);
// Exports
export {store, persistor};
当我向服务器发出请求时,我使用三种类型的动作分派,例如
LOGIN_REQUEST
LOGIN_SUCCESS
LOGIN_FAILURE
并根据请求 LOGIN_REQUEST 调度操作(将加载状态设置为true以加载动画并禁用登录按钮),成功请求后将 LOGIN_SUCCESS 调度并 LOGIN_FAILURE :请求失败(并将加载状态设置为false) 这是减速器
...
case LOGIN_SUCCESS: {
return {
...state,
user: action.payload,
loading : false
};
}
case LOGIN_REQUEST: {
return {
...state,
loading: true,
};
}
case LOGIN_FAILURE: {
return {
...state,
loading: false,
};
}
...
以这种方式加载动画效果很好。
如果在请求进行过程中应用程序关闭,并且加载状态仍然为true(因为未调度LOGIN_FAILURE或LOGIN_SUCCESS操作),则会出现问题,
下次打开应用程序时,加载状态为true,并且出现加载动画
我研究了一些解决方案,例如在 persist / REHYDRATE 之类的自动调度操作上更新状态
...
case "persist/REHYDRATE": {
return {
...state,
loading : false
};
}
...
OR
黑名单状态,例如 reducerName.loading ,例如
...
storage: AsyncStorage,
// Whitelist (Save Specific Reducers)
whitelist: ['authReducer',],
// Blacklist (Don't Save Specific Reducers)
blacklist: ['authReducer.loading'],
...
有没有更好的方法来解决这种情况 谢谢
答案 0 :(得分:1)
您可以使用AppState
进行检查并禁用加载。
import {AppState} from 'react-native';
useEffect(() => {
AppState.addEventListener("change", _handleAppStateChange);
return () => {
AppState.removeEventListener("change", _handleAppStateChange);
};
}, []);
const _handleAppStateChange = (nextAppState) => {
if (appState.current === 'active' && nextAppState.match(/inactive|background/)) {
//check if loading is true, set is to false if it is
}
appState.current = nextAppState;
setAppStateVisible(appState.current);
};