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

Ste*_*sen 18 react-native

有什么方法可以检测反应原生应用的首次启动和初始启动,以显示入门/介绍屏幕?

mar*_*oyo 34

你的逻辑应该遵循这个:

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/>
       }
}
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你

  • 问题是,真的不是一个字符串.用引号括起来然后就行了 (4认同)

Eir*_*sse 16

我对马丁纳罗的建议做了一些调整.AsyncStorage.setItem应该设置字符串值而不是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;
  }
}
Run Code Online (Sandbox Code Playgroud)

然后可以在您需要的任何地方导入此功能.请注意,在等待异步函数检查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>
    ;
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 因为它是一个键值字符串存储,并且 AsyncStorage 文档指定该值应该是一个字符串 [https://facebook.github.io/react-native/docs/asyncstorage#setitem](https://facebook.github .io/react-native/docs/asyncstorage#setitem)。我不是 100% 确定,但我假设如果您尝试存储布尔值,它将被转换为字符串。当稍后使用“getItem”获取它时,我假设它不会自动转换回布尔值。 (2认同)

ale*_*ogo 7

2022 年:请注意,react-native 中的 AsyncStorage 已被弃用。请改用react-native-async-storage/async-storage

自定义挂钩:

import React, { useState } from "react";
import AsyncStorage from "@react-native-async-storage/async-storage";

async function checkIfFirstLaunch() {
  try {
    const hasFirstLaunched = await AsyncStorage.getItem("@usesr_onboarded");
    if (hasFirstLaunched === null) {
      return true;
    }
    return false;
  } catch (error) {
    return false;
  }
}

const useGetOnboardingStatus = () => {
  const [isFirstLaunch, setIsFirstLaunch] = useState(false);
  const [isFirstLaunchIsLoading, setIsFirstLaunchIsLoading] = useState(true);

  React.useEffect(async () => {
    const firstLaunch = await checkIfFirstLaunch();
    setIsFirstLaunch(firstLaunch);
    setIsFirstLaunchIsLoading(false);
  }, []);

  return {
    isFirstLaunch: isFirstLaunch,
    isLoading: isFirstLaunchIsLoading,
  };
};

export default useGetOnboardingStatus;
Run Code Online (Sandbox Code Playgroud)

用法:

import useGetOnboardingStatus from "../../utils/useGetOnboardingStatus";

const { isFirstLaunch, isLoading: onboardingIsLoading } =
    useGetOnboardingStatus();
Run Code Online (Sandbox Code Playgroud)

正如 Eirik Fosse 提到的:您可以使用 onboardingIsLoading 在等待响应时返回 null。