IT이야기

반응형 최초 발사를 탐지하는 방법

cyworld 2022. 3. 24. 21:58
반응형

반응형 최초 발사를 탐지하는 방법

온보드/초기 출시 화면을 보여주기 위해 반응형 앱의 최초 및 초기 출시 상황을 감지하는 좋은 방법은 무엇인가?

당신의 논리는 다음과 같아야 한다:

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

도움이 되길 바래.

나는 마르티나로요의 제안에 몇 가지 조정을 했다. AsyncStorage.setItembool이 아니라 문자열 값을 설정해야 한다.

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

참조URL: https://stackoverflow.com/questions/40715266/how-to-detect-first-launch-in-react-native

반응형