我创建了一个使用 React Native 的简单应用程序AppState:
import React, {Component} from 'react'
import {AppState, Text , View} from 'react-native'
export default class AppStateExample extends React.Component {
constructor(props){
super(props);
this.state = {
name:'not change'
}
}
componentDidMount() {
AppState.addEventListener('change', this._handleAppStateChange);
}
componentWillUnmount() {
AppState.removeEventListener('change', this._handleAppStateChange);
}
_handleAppStateChange = (nextAppState) => {
if(AppState.currentState=='background'){
console.log('background mode');
this.setState({name:'back'});
}
if(AppState.currentState =='active'){
//...
}
};
render() {
return (
<View>
<Text>State Name : {this.state.name}</Text>
</View>
);
}
}
Run Code Online (Sandbox Code Playgroud)
当我尝试将应用程序从前台切换到后台,然后从后台切换到前台时,console.log('background mode');效果很好并且控制台打印'background mode'
但
不起作用this.setState({name:'back'});,我'not change'在视图中看到文字
那是因为,AppState.addEventListener('change', this._handleAppStateChange);报名太晚了。在加载主要组件之前,您可能希望在应用程序中首先监听 AppState 并可能通过状态管理库传递值
| 归档时间: |
|
| 查看次数: |
12172 次 |
| 最近记录: |