2016-11-21 145 views
8

爲了顯示入門/介紹屏幕,檢測反應原生應用程序的首次發佈和初次發佈的好方法是什麼?如何檢測首次發佈的反應本機應用程序

+1

考慮使用'AsyncStorage':http://facebook.github.io/react-native/releases/0.37/docs/asyncstorage.html – Cherniv

+0

但由於這樣的事實,AsyncStorage是異步〜〜,響應通過回調返回,我不能讓視圖等待。或者我錯過了什麼? –

+0

你可以使用'View'狀態來玩,可以說你可以在LocalStorage的響應中顯示一些'ActivityIndi​​cator',然後隱藏ActivityIndi​​cator,像'this.setState({shouldShowIndicator:false})'' – Cherniv

回答

15

您的邏輯應遵循此:

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/> 
     } 
} 

希望它可以幫助

3

我做了一些調整martinarroyo的建議。 AsyncStorage.setItem應該設置一個字符串值而不是布爾值。

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; 
    } 
} 

該功能可以導入任何你需要的地方。請注意,在等待異步函數檢查AsyncStorage時,您應該呈現null(或別的聰明)。

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 ? 
     <Text>This is the first launch</Text> : 
     <Text>Has launched before</Text> 
    ; 
    } 
} 
相關問題