【发布时间】:2021-07-26 14:04:55
【问题描述】:
我创建了一个使用 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>
);
}
}
当我尝试将应用程序从前台切换到后台,然后从后台切换到前台时,console.log('background mode'); 工作得很好并且控制台
打印'background mode'
但是
this.setState({name:'back'}); 不起作用,我看到 'not change' 文本显示在视图中
【问题讨论】:
-
您找到
this.setState不起作用的任何原因吗?就我而言,setState根本不存在,这很奇怪。
标签: react-native react-native-android