首页 > 解决方案 > 如何在反应原生应用程序中检测应用程序首次启动?

问题描述

在我的场景中,我有三个不同的屏幕,如Page1, Page2, Page3. 在这里,如果用户上次访问页面 2,那么下次如果用户打开应用程序,而不是显示 page1 需要显示 page2。如何使用react-native应用程序实现这一点?

我尝试使用async存储但不知道如何管理多个页面

AsyncStorage.getItem("alreadyLaunched").then(value => {
            if(value == null){
                 AsyncStorage.setItem('alreadyLaunched', true); // No need to wait for `setItem` to finish, although you might want to handle errors
                 this.setState({firstLaunch: true});
            }
            else{
                 this.setState({firstLaunch: false});
            }}) // Add some error handling, also you can simply do this.setState({fistLaunch: value == null})

应用程序.js

import { createAppContainer } from 'react-navigation';
import { createStackNavigator} from 'react-navigation-stack';

import FirstPage from './pages/FirstPage';
import SecondPage from './pages/SecondPage';
import ThirdPage from './pages/ThirdPage';

//import all the screens we are going to switch 
const App = createStackNavigator({
   //Constant which holds all the screens like index of any book 
   FirstPage: { screen: FirstPage, header: null},
   SecondPage: { screen: SecondPage,  headerLeft: null, headerBackTitle: null}, 
   ThirdPage: { screen: ThirdPage}, 
  },
  {
    initialRouteName: 'FirstPage',
  }
);
export default createAppContainer(App);

标签: javascriptandroidiostypescriptreact-native

解决方案


您应该使用 AsyncStorage 来存储当前屏幕,因此无论何时从一个屏幕移动到另一个屏幕,您都应该调用

AsyncStorage.setItem('screen', 'nameOfYourScreen')

在 App.js 中你应该调用

AsyncStorage.getItem('screen');

并将其影响到 initialRouteName

PS:getItem() 是异步的。


推荐阅读