【问题标题】:Is there a hook that runs on application start up?是否有在应用程序启动时运行的挂钩?
【发布时间】:2023-01-20 09:05:29
【问题描述】:

我想知道是否有一个包含在应用程序打开时运行的挂钩的库,或者是否有一种方法可以在应用程序打开时运行函数(仅在不使用任何定时函数的情况下)

【问题讨论】:

  • 您可以在入口文件 (App.js) 中的 componentDidMount() 中执行此操作,或者如果它是基于函数的组件,则可以使用 useEffect

标签: react-native expo


【解决方案1】:

好像没有这样的库。

【讨论】:

    【解决方案2】:

    我给你举个例子:

    import React, { useState } from 'react'
    
    const Player = props => {
    const [playerList, setPlayer] = useState([ ])
    
    useEffect(() => {
    fetch('URL')
      .then(res => res.json())
      .then(fetchedPlayers => setPlayer(fetchedPlayers))
    }, [ ])
    }
    

    我们传递一个空数组作为第二个参数。这将告诉 React 只有在第一次渲染时才调用第一个 useEffect() 函数,就像我们对 componentDidMount() 所做的那样。

    【讨论】:

    • 我了解这种方法,但每次打开应用程序时我都需要运行该功能。在不使用任何定时功能的情况下,id 宁愿在用户每次打开它时更新我的​​应用程序的数据。
    • 如果你在 App.js 中使用 useEffect 作为启动画面,每次用户打开应用程序时都会更新数据
    • 是的,那绝对有效!我也开始在主屏幕中使用 useEffect 来更新数据(这是因为我的应用程序需要注册并且在记录之前不需要加载信息)。
    【解决方案3】:

    如果您在代码中使用功能组件和挂钩,下面的挂钩应该会有所帮助:

    import { useEffect, useRef } from "react";
    import { AppState } from "react-native";
    
    interface UseAppStateHookProps {
      onAppEnterForeground: () => void;
    }
    
    export const useAppState = ({ onAppEnterForeground }: UseAppStateHookProps) => {
      const appState = useRef(AppState.currentState);
    
      useEffect(() => {
        const subscription = AppState.addEventListener(
          "change",
          _handleAppStateChange
        );
        return () => {
          subscription.remove();
        };
      }, []);
    
      const _handleAppStateChange = (nextAppState) => {
        if (
          appState.current.match(/inactive|background/) &&
          nextAppState === "active"
        ) {
          onAppEnterForeground();
        }
    
        appState.current = nextAppState;
      };
    
      return { appState };
    };
    

    然后在要实现钩子的功能组件中,添加如下内容:

      const appState = useAppState({
        onAppEnterForeground: () => {
          // your code here
        },
      });
    

    注意:这是基于 React Native 在AppState 上的文档。

    【讨论】:

      猜你喜欢
      • 2011-01-27
      • 2012-05-03
      • 1970-01-01
      • 1970-01-01
      • 2018-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多