cin*_*l45 2 android react-native
在 web 上使用 React,很容易估计组件何时挂载或卸载,因为用户如何访问/离开某些路由。
如果我想在页面加载时获取一些数据并使用该数据动态显示组件,我会执行以下操作:
componentWillMount() {
this.props.fetchData();
}
Run Code Online (Sandbox Code Playgroud)
如果他们退出此页面并稍后回来,我知道他们回来了,所以我可以挂载并显示一些新数据。
但是,使用 React-Native for Android,有些我不明白。当用户通过按下主页按钮或概览按钮离开应用程序时,他们留下的组件不会卸载。因此,如果他们返回应用程序,组件将不会被挂载(它已经被挂载),因此,显示的数据不会被刷新。
如果用户使用“后退”按钮离开应用程序,这是个好消息,因为组件将卸载,因此当用户返回时,示例 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});
}
Run Code Online (Sandbox Code Playgroud)
您可以在 React Native 的官方文档中找到更多信息。
| 归档时间: |
|
| 查看次数: |
1596 次 |
| 最近记录: |