React-Native:当应用程序处于后台时更改状态

Roo*_*oox 5 react-native

我创建了一个使用 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'在视图中看到文字

age*_*unt 0

那是因为,AppState.addEventListener('change', this._handleAppStateChange);报名太晚了。在加载主要组件之前,您可能希望在应用程序中首先监听 AppState 并可能通过状态管理库传递值

  • 哦。那是一个巨大的。您需要检查iOS的后台执行https://developer.apple.com/library/content/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html#//apple_ref/doc/uid/TP40007072-CH4-SW1。有一些现有的本机模块可以做到这一点。https://github.com/transistorsoft/react-native-background-geolocation https://github.com/timfpark/react-native-location (2认同)