返回 React Native 应用程序时调用函数

Tho*_*Byy 2 reactjs react-native expo

我有一个使用此代码的应用程序:Linking.openURL('google.navigation:q='+latitude+'+'+longitude)在我的 React Native Expo 应用程序中退出到谷歌地图。对于 Android(和 iOS),您可以使用手机的后退按钮返回到之前的应用程序。我想知道当我的应用程序重新出现时如何调用函数。我的应用程序中有一些 GPS 数据,我希望在它们移动到某个位置后一旦返回我的应用程序就重新更新我的数据。我找到了这个....

componentWillMount() {
    const { navigation } = this.props;
    this.focusListener = navigation.addListener('didFocus', () => {
       // The screen is focused
       // Call any action
    });
}
Run Code Online (Sandbox Code Playgroud)

但当我从地图回来时它似乎没有打电话..,

这是接近还是我做的完全错误?

谢谢

Len*_*rod 6

你可以使用AppState来实现它。

componentDidMount(){
 AppState.addEventListener('change', this.handleAppStateChange);
}

handleAppStateChange = (nextAppState) => {
        //the app from background to front
        if (this.state.appState.match(/inactive|background/) && nextAppState === 'active') {

        }
//save the appState
this.setState({ appState: nextAppState });
    }

Run Code Online (Sandbox Code Playgroud)

源代码注释说:

 *AppStateIOS can tell you if the app is in the foreground or background,
 * and notify you when the state changes.
 *  * AppStateIOS is frequently used to determine the intent and proper 
 * behavior
 * when handling push notifications.
 *  * iOS App States
 *      active - The app is running in the foreground
 *      background - The app is running in the background. The user is 
 *either in another app or on the home screen
 *      inactive - This is a transition state that currently never happens 
 * for typical React Native apps.
Run Code Online (Sandbox Code Playgroud)

不同状态含义:

  • active - 应用程序正在前台运行

  • 背景 - 应用程序在后台运行。
    用户是:
    1、在另一个应用程序中
    2、在主屏幕
    [Android] 上的另一个 Activity 上(即使它是由您的应用程序启动的)

  • [iOS] 非活动 - 这是在前台和后台之间转换时以及在不活动期间(例如进入多任务视图或来电时)发生的状态

你必须小心处理 android 的状态。