React-Native:当应用在后台时更改状态

时间:2018-05-22 10:38:53

标签: react-native react-native-android

我创建了一个简单的应用程序,熟悉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'文字

3 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

我会选择一个包装所有endPoint的开关 注意:获取appState状态AppState.currentState

&#13;
&#13;
this.state = {
  appState: AppState.currentState
  // https://facebook.github.io/react-native/docs/appstate.html
};


componentWillMount() {
  AppState.addEventListener('change', () => this._handleAppStateChange());
};


componentWillUnmount() {
  AppState.removeEventListener('change', () => this._handleAppStateChange());
}

_handleAppStateChange() {
  // https://facebook.github.io/react-native/docs/appstate.html
  const {
    appState
  } = this.state;
  console.warn({
    appState
  })

  this.fetchData().catch(error => error);

  switch (appState) {
    case 'active': //The app is running in the foreground
      this.onStart();
      break;
    case 'background': // The app is running in the background. The user is either
      this.onEnd();
      console.warn('background');
      break;

    case 'inactive':
      // The app transitioning between foreground & background or entering the Multitasking view or in the event of an incoming call
      console.warn('Inactive');
      break;

    default:
      console.warn('_handleAppStateChange default');
  }
}
&#13;
&#13;
&#13;

答案 2 :(得分:0)

实际上,基于功能组件的AppStateReact Native Docs的更改,我更喜欢编写如下代码:

import { useRef, useState, useEffect } from "react";
import { AppState } from "react-native";

const AppStateManager = () => {
  const appState = useRef(AppState.currentState);
  const [appStateVisible, setAppStateVisible] = useState(appState.current);

  useEffect(() => {
    AppState.addEventListener("change", handleAppStateChange);

    return () => {
      AppState.removeEventListener("change", handleAppStateChange);
    };
  }, []);

  const handleAppStateChange = (nextAppState) => {
    if (
      appState.current.match(/inactive|background/) &&
      nextAppState === "active"
    ) {
      console.log("App has come to the foreground!");
    }

    appState.current = nextAppState;
    setAppStateVisible(appState.current);
    console.log("AppState", appState.current);
  };

  return null;
};

export default AppStateManager;

当然,我们可以像React组件一样在项目的根目录中使用该组件:

~~~
  <App>
    ~~
    <AppStateManager />
    ~~
.
.
.