React Native 是否有在应用程序启动时运行的钩子?

7rfyedvj  于 2023-01-21  发布在  React
关注(0)|答案(3)|浏览(152)

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

bqujaahr

bqujaahr1#

好像没有这样的图书馆。

jaxagkaj

jaxagkaj2#

我给予你们举个例子:

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()时才调用第一个useEffect()函数,就像我们对componentDidMount()所做的那样。

mnemlml8

mnemlml83#

如果你在代码中使用了函数组件和钩子,下面的钩子会有所帮助:

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上的文档。

相关问题