We are building a React Native app that uses redux-persist to store the app state, including the navigation state. I would like for this app to behave like a native app in terms of navigation:
When a native Android app goes into the background, is eventually stopped by the OS and is then moved into the foreground, it will resume in the Activity where the user previously left off. If the same app is killed by the user (or a crash), it will open at the main Activity.
For a RN app, this means that redux-persist should persist and restore the navigation state in the componentWillMount of the app, but only if the app was not killed by the user.
The following code works:
componentWillMount() {
if (global.isRelaunch) {
// purge redux-persist navigation state
}
global.isRelaunch = true;
...
But it looks hackish and I also do not understand why the global scope survives.
What is the proper way to detect whether an RN app was re-opened from the background? (ideally with iOS support)
React Navigation is written in JavaScript and does not directly use the native navigation APIs on iOS and Android.
React Native benefitsIt also allows for sharing and reusing most of the code between iOS and Android. By reusing the same code, you not only speed up the development process, but also require less resources: there is no need for separate iOS and Android teams.
LifecycleOwner is a single method interface that denotes that the class has a Lifecycle . It has one method, getLifecycle() , which must be implemented by the class.
You will need Node, the React Native command line interface, a JDK, and Android Studio. While you can use any editor of your choice to develop your app, you will need to install Android Studio in order to set up the necessary tooling to build your React Native app for Android.
You should take a look to AppState which is an api that provided by react-native
check this example:
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>
);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With