How to detect first launch in react-native

前端 未结 2 1134
臣服心动
臣服心动 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条回答
  •  一向
    一向 (楼主)
    2020-12-23 11:10

    Your logic should follow this:

    class MyStartingComponent extends React.Component {
        constructor(){
            super();
            this.state = {firstLaunch: null};
        }
        componentDidMount(){
            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})
        }
        render(){
           if(this.state.firstLaunch === null){
               return null; // This is the 'tricky' part: The query to AsyncStorage is not finished, but we have to present something to the user. Null will just render nothing, so you can also put a placeholder of some sort, but effectively the interval between the first mount and AsyncStorage retrieving your data won't be noticeable to the user.
           }else if(this.state.firstLaunch == true){
               return 
           }else{
               return 
           }
    }
    

    Hope it helps

提交回复
热议问题