javascript - 在应用程序进入前台之前记住状态
问题描述
我有一个反应原生项目,我必须实现一个功能,当应用程序处于非活动状态时,它会呈现一个徽标屏幕,而当应用程序处于活动状态时,它会呈现应用程序。
我能够做到这一点,但我现在的问题是例如。如果我的主屏幕是主屏幕,并且当我在我的应用程序和另一个应用程序之间导航时我当前在我的个人资料屏幕上,然后返回我的应用程序,我将返回主屏幕而不是个人资料屏幕。
我该如何解决?
我应该将我的应用程序的当前状态保存在 AsyncStorage 中吗?
我也在使用 React Context API 而不是 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>
</>
);
推荐阅读
- reactjs - 如何使用gridfs通过axios发送图像?
- qliksense - 对度量进行分类以用作维度
- linux-kernel - 修改 linux 中的 write 系统调用给出错误的 RIP 值错误
- php - 我需要替换变量 php ->
- java - 从日期输入打印星期几
- reactjs - React - 无法使用`this`在回调函数中调用组件方法
- vb.net - 在 VB.net 中查找数据表中的重复行
- kotlin - 引用接口中定义的属性,kotlin
- javascript - React Native Firebase - createUserWithEmailAndPassword:第一个参数“电子邮件”必须是有效字符串
- c++ - MVC 设计模式 QT