在网络上使用 React,可以根据用户访问/离开某些路由的方式轻松估计组件何时安装或卸载。
如果我想在页面加载时获取一些数据并使用该数据动态显示组件,我会这样做:
componentWillMount() {
this.props.fetchData();
}
如果他们退出此页面并稍后返回,我知道他们回来了,这样我就可以安装并显示一些新数据。
但是,在使用 Android 版 React-Native 时,有一些我不明白的地方。当用户通过按“主页”按钮或“概述”按钮离开应用程序时,他们留下的组件不会卸载。因此,如果他们返回应用程序,该组件将不会被安装(它已经安装了),因此,显示的数据不会刷新。
如果用户使用“后退”按钮离开应用程序,这是个好消息,因为组件将卸载,因此当用户返回时,示例 fetchData 函数将再次触发。
使用“主页”和“概览”按钮跟踪用户行为时的一般做法是什么?
最佳答案
您可以像这样监听应用程序状态变化:
import {AppState} from 'react-native';
class AppStateExample extends Component {
state = {
appState: AppState.currentState
}
componentDidMount() {
AppState.addEventListener('change', this._handleAppStateChange);
}
componentWillUnmount() {
AppState.removeEventListener('change', this._handleAppStateChange);
}
_handleAppStateChange = (nextAppState) => {
if (this.state.appState.match(/inactive|background/) && nextAppState === 'active') {
console.log('App has come to the foreground!')
}
this.setState({appState: nextAppState});
}
更多信息可以在React Native官方documentation上找到.
关于android - 当用户使用“主页”或“概述”按钮离开应用程序时,如何更新 React Native 中的组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42931415/