React Native,Android生命周期和导航

sAm*_*vdP 12 javascript react-native react-native-android redux-persist

我们正在构建一个React Native应用程序,它使用redux-persist来存储应用程序状态,包括导航状态.我想这个应用程序在导航方面表现得像本机应用程序:

当原生Android应用程序进入后台时,最终会被操作系统停止,然后移动到前台,它将在用户之前停止的活动中恢复.如果同一个应用程序被用户杀死(或崩溃),它将在主Activity上打开.

对于RN应用程序,这意味着redux-persist应该持久化并恢复应用程序的componentWillMount中的导航状态,但前提是应用程序未被用户杀死.

以下代码有效:

componentWillMount() {
  if (global.isRelaunch) {
    // purge redux-persist navigation state
  }
  global.isRelaunch = true;
...
Run Code Online (Sandbox Code Playgroud)

但它看起来很乱,我也不明白为什么全球范围仍然存在.

检测RN应用程序是否从后台重新打开的正确方法是什么?(理想情况下支持iOS)

sem*_*gay 3

你应该看看AppState这是一个由react-native

检查这个例子:

import React, {Component} from 'react'
import {AppState, Text} 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});
  }

  render() {
    return (
      <Text>Current state is: {this.state.appState}</Text>
    );
  }

}
Run Code Online (Sandbox Code Playgroud)

  • 谁杀死了这个进程确实很重要!如果用户明确终止了应用程序,我想重置导航状态。但是,如果 Android 操作系统终止了该进程,我不想重置状态 - 在本机应用程序上,在这种情况下将使用 savingInstanceState 来恢复状态。 (3认同)