在应用程序进入前台之前记住状态 [英] Remembering state before app goes in foreground
问题描述
我有一个react native项目,我必须实现一个功能,当应用程序处于非活动状态时,它将呈现徽标屏幕,而当应用程序处于活动状态时,则将呈现应用程序.
I have a react native project and i have to implement a feature that when app is inactive it renders a logo screen and when app is active it renders the app.
我能够做到这一点,但是我现在的问题是.如果我的主屏幕是主屏幕,并且当我在我的应用程序和另一个应用程序之间导航时,我当前在个人资料屏幕上,然后返回我的应用程序,我将返回主屏幕,而不是个人资料屏幕.
I was able to accomplish this but my problem now is eg. if my main screen is the home screen and i am currently on my profile screen when i navigate between my app and another app then go back to my app i return to the home screen instead of the profile screen.
我该如何解决?
我应该在AsyncStorage中将当前状态保存在我的应用程序中吗?
Should i save the current state on my app in AsyncStorage?
我也在使用React Context API,而不是redux.
I am also using React Context API not redux.
这是我要求的代码:
const[isReady, setIsReady] = useState(false);
const[user,setUser]=useState();
const[authenticated,setAuthenticated]=useState();
const appState = useRef(AppState.currentState);
const [appStateVisible, setAppStateVisible] =useState(appState.current);
const _handleAppStateChange = (nextAppState) => {
if (
appState.current.match(/inactive|background/) &&
nextAppState === "active"
) {
console.log("App has come to the foreground!");
}
appState.current = nextAppState;
setAppStateVisible(appState.current);
console.log("AppState", appState.current);
};
useEffect(() => {
AppState.addEventListener("change", _handleAppStateChange);
return () => {
AppState.removeEventListener("change", _handleAppStateChange);
};
}, []);
const restoreUser = async () => {
const user = await storage.getUser();
if (user) setUser(user);
};
if (!isReady)
return (
<AppLoading
startAsync={restoreUser}
onFinish={() => setIsReady(true)}
onError={console.warn}
/>
);
return(
(appState.current)==='active'?
<AuthContext.Provider value=
{{user,setUser,authenticated,setAuthenticated}}>
<NavigationContainer theme={navigationTheme} ref={navigationRef}>
{
(user&&authenticated)?<AppNavigator/>
:(user)?<PasscodeNavigator/>
:<AuthNavigator/>
}
</NavigationContainer>
</AuthContext.Provider>
:
<SplashScreen/>
推荐答案
当应用程序状态更改时,您可以显示/隐藏模式显示的Splash而不是屏幕
import { Modal } from "react-native";
const [modalVisible, setModalVisible] = useState(false);
const _handleAppStateChange = nextAppState => {
if (
appState.current.match(/inactive|background/) &&
nextAppState === 'active'
) {
setModalVisible(false);
} else {
setModalVisible(true);
}
};
return (
<>
<AuthContext.Provider
value={{ user, setUser, authenticated, setAuthenticated }}
>
<NavigationContainer theme={navigationTheme} ref={navigationRef}>
{user && authenticated ? (
<AppNavigator />
) : user ? (
<PasscodeNavigator />
) : (
<AuthNavigator />
)}
</NavigationContainer>
</AuthContext.Provider>
<Modal animationType="slide" transparent={true} visible={modalVisible}>
<SplashScreen />
</Modal>
</>
);
这篇关于在应用程序进入前台之前记住状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!