阵营原住民 - 渲染时应用进入前台

阵营原住民 - 渲染时应用进入前台

问题描述:

我有是基于一些异步数据的简单显示。阵营原住民 - 渲染时应用进入前台

我的代码是这样的:

componentDidMount() { 
    asynFunctionCall(result => { 
    this.setState({stateVariable: result}); 
    }); 
} 

而且我用的是状态变量stateVariable,以决定是否要显示<Text>组件:

render() { 
    return (
    <View> 
     {this.state.stateVariable && 
     <Text> Special Message </Text> 
     } 
    </View> 
); 
} 

我要的是asyncFunctionCall是每当应用程序进入前台时运行,以便用户可以离开应用程序,执行一些操作(这可能会影响异步调用的结果),然后返回到应用程序并使显示适当更新。

这似乎是一个标准的应用程序的行为,我不知道如果REACT原生的生命周期API有一个标准的方式来支持它,但我没有找到它。

我怎样才能做到这一点的行为,具有生命周期的功能或以其他方式?

+0

如果您正在使用导航,你可以捕捉它的'onDidFocus',http://facebook.github.io/react-native/releases/0.37/docs/navigator.html #ondidfocus – Cherniv

是的。您可以使用AppState https://facebook.github.io/react-native/docs/appstate.html API。

我会建议在应用的开始添加这个地方,并相应地协调的意见。

届时AppState应该基本能工作于iOS,但Android的后台活动随时触发自己的代码外的本机模块被触发,e.g拍摄照片。检测家庭或最近的应用按钮点击方式会更好。这是因为来自社交媒体或照片等其他应用程序的应用程序中的片段也会触发后台状态,这是您不需要的,因为它们仍然在应用程序中,从相机中将照片添加到配置文件等。您可以轻松检测到家中和最近的应用程序按钮点击Android的反应本地家庭按下。这个库只是公开android按钮事件。

首先安装库npm i react-native-home-pressed --save,然后链接它react-native link。然后重新构建您的应用程序并添加以下代码片段。

import { DeviceEventEmitter } from 'react-native' 
 

 
class ExampleComponent extends Component { 
 
    componentDidMount() { 
 
    this.onHomeButtonPressSub = DeviceEventEmitter.addListener(
 
    'ON_HOME_BUTTON_PRESSED', 
 
    () => { 
 
     console.log('You tapped the home button!') 
 
    }) 
 
    this.onRecentButtonPressSub = DeviceEventEmitter.addListener(
 
    'ON_RECENT_APP_BUTTON_PRESSED', 
 
    () => { 
 
     console.log('You tapped the recent app button!') 
 
    }) 
 
    } 
 
    componentWillUnmount(): void { 
 
    if (this.onRecentButtonPressSub) this.onRecentButtonPressSub.remove() 
 
    if (this.onHomeButtonPressSub) this.onHomeButtonPressSub.remove() 
 
    } 
 
}