【发布时间】:2023-01-20 09:05:29
【问题描述】:
我想知道是否有一个包含在应用程序打开时运行的挂钩的库,或者是否有一种方法可以在应用程序打开时运行函数(仅在不使用任何定时函数的情况下)
【问题讨论】:
-
您可以在入口文件 (App.js) 中的
componentDidMount()中执行此操作,或者如果它是基于函数的组件,则可以使用useEffect。
标签: react-native expo
我想知道是否有一个包含在应用程序打开时运行的挂钩的库,或者是否有一种方法可以在应用程序打开时运行函数(仅在不使用任何定时函数的情况下)
【问题讨论】:
componentDidMount() 中执行此操作,或者如果它是基于函数的组件,则可以使用 useEffect。
标签: react-native expo
好像没有这样的库。
【讨论】:
我给你举个例子:
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() 所做的那样。
【讨论】:
如果您在代码中使用功能组件和挂钩,下面的挂钩应该会有所帮助:
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 上的文档。
【讨论】: