How to detect first launch in react-native

前端 未结 2 1143
臣服心动
臣服心动 2020-12-23 10:10

What is a good way to detect the first and initial launch of an react-native app, in order to show an on-boarding/introductory screen ?

2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-23 11:02

    I made some adjustments to martinarroyo's suggestion. AsyncStorage.setItem should set a string value and not a bool.

    import { AsyncStorage } from 'react-native';
        
    const HAS_LAUNCHED = 'hasLaunched';
    
    function setAppLaunched() {
      AsyncStorage.setItem(HAS_LAUNCHED, 'true');
    }
    
    export default async function checkIfFirstLaunch() {
      try {
        const hasLaunched = await AsyncStorage.getItem(HAS_LAUNCHED);
        if (hasLaunched === null) {
          setAppLaunched();
          return true;
        }
        return false;
      } catch (error) {
        return false;
      }
    }
    

    This function can then be imported wherever you need it. Note that you should render null (or something else clever) while waiting for the async function to check AsyncStorage.

    import React from 'react';
    import { Text } from 'react-native';
    import checkIfFirstLaunch from './utils/checkIfFirstLaunch';
    
    export default class App extends React.Component {
      constructor(props) {
        super(props);
    
        this.state = {
          isFirstLaunch: false,
          hasCheckedAsyncStorage: false,
        };
      }
    
      async componentWillMount() {
        const isFirstLaunch = await checkIfFirstLaunch();
        this.setState({ isFirstLaunch, hasCheckedAsyncStorage: true });
      }
    
      render() {
        const { hasCheckedAsyncStorage, isFirstLaunch } = this.state;
    
        if (!hasCheckedAsyncStorage) {
          return null;
        }
    
        return isFirstLaunch ?
          This is the first launch :
          Has launched before
        ;
      }
    }
    

提交回复
热议问题