【问题标题】:React Native: How to detect if an app has come to the foreground on start/after closing the app from AppSwitcher?React Native:如何检测应用程序是否在启动时/从 AppSwitcher 关闭应用程序后进入前台?
【发布时间】:2021-12-31 03:37:21
【问题描述】:

我希望能够在我的 React Native 应用程序进入前台时订阅事件监听器。

React Native 有 AppState 这些 API,官方文档中有以下示例

const AppStateExample = () => {
  const appState = useRef(AppState.currentState);
  const [appStateVisible, setAppStateVisible] = useState(appState.current);

  useEffect(() => {
    const subscription = AppState.addEventListener("change", nextAppState => {
      if (
        appState.current.match(/inactive|background/) &&
        nextAppState === "active"
      ) {
        console.log("App has come to the foreground!");
      }

      appState.current = nextAppState;
      setAppStateVisible(appState.current);
    });

    return () => {
      subscription.remove();
    };
  }, []);

  return (
      <Text>Current state is: {appStateVisible}</Text>
  );
};

我的问题是当应用程序第一次启动时,或者在我通过向上滑动从 AppSwitcher 关闭 iOS 上的应用程序之后,这不起作用。

从 AppSwitcher 关闭应用后第一次启动时,如何检测状态变化?据我所知,在这种情况下,状态是background

【问题讨论】:

    标签: android ios reactjs react-native


    【解决方案1】:

    尝试将 if 语句更改为如下内容:

      if (
        appState.current.match(/inactive|background/) &&
        nextAppState === 'active'
      ) {
        console.log('App has come to the foreground!');
      } else {
        console.log('App state', nextAppState);
      }
    

    如果您启动应用程序然后向上滑动将其关闭,您应该会看到以下日志输出:

     LOG  Running "appstatetest" with {"rootTag":1,"initialProps":{}}
     LOG  App state active
     LOG  App state inactive
     LOG  App state background
    

    应用程序首次启动时正在输出应用程序状态。当您开始向上滑动时,正在输出应用状态非活动状态,并在应用关闭时输出应用状态背景。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-08
      • 2019-12-20
      • 2023-02-10
      • 1970-01-01
      • 2018-04-19
      • 2011-03-10
      相关资源
      最近更新 更多