如何检测 react-native 中的首次启动

新手上路,请多包涵

什么是检测 react-native 应用程序的首次和初始启动以显示入门/介绍屏幕的好方法?

原文由 Steffen Christensen 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1k
1 个回答

你的逻辑应该遵循这个:

 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 <FirstLaunchComponent/>
       }else{
           return <NotFirstLaunchComponent/>
       }
}

希望能帮助到你。

原文由 martinarroyo 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
logo
Stack Overflow 翻译
子站问答
访问
宣传栏