如何优雅地关闭 React Native Application for Android



我是 React Native Application 的新手。我使用以下代码在单击按钮时关闭应用程序。

BackHandler.exitApp();
return false;

但是应用程序未正确结束,仍位于任务栏中。因此,当我尝试再次打开应用程序时,componentWillMount永远不会执行。

我正在使用以下版本的 React Native。

  • 反应本机 CLI:2.0.1
  • 反应原生:0.55.4

关于如何干净地关闭 React 本机应用程序的任何帮助或建议?

提前谢谢。

谷歌和苹果不会建议强制退出应用程序,所以你应该避免这样做,以获得更好的用户体验。

如果您需要在应用程序从后台返回时调用函数,您可以使用 react-native 的 Appstate API。使用 Appstate,您可以侦听应用程序状态(活动、后台和非活动(并运行所需的函数。

AppState可以告诉您应用程序是在前台还是后台, 并在状态更改时通知您。

下面是请求数据和刷新每次屏幕返回前台时的列表的示例。

样本

import React, { Component } from 'react';
import { Text, View, FlatList, StyleSheet, AppState } from 'react-native';
export default class App extends Component {
state = {
data: []
}
requestItems = () => {
fetch('someurl').then((response) => response.json()).then((responseJSON) => this.setState({data: responseJSON.data}))
}
componentDidMount() {
this.requestItems()
AppState.addEventListener('change', this.requestItems);
}
componentWillUnmount() {
AppState.removeEventListener('change', this.requestItems);
}
renderItem = ({item}) => <Text>{item.text}</Text>
render() {
if (this.state.data.lenght === 0) return <Text>{'Loading'}</Text>
return (
<View style={styles.container}>
<FlatList data={this.state.data} renderItem={this.renderItem} keyExtractor={(item) => item.id} />
</View>
);
}
}  

最新更新