Vinicius Morais
Vinicius Morais

Reputation: 595

How use navigate properly

I'm Making a App with navigate. My component that make the navigate has this code:

const AppNavigator = createStackNavigator({
    Articles: { screen: ArticlesScreen },
    Profile: { screen: ProfileScreen},
    ModalProfile: { screen: ModalProfile},
},
{
    cardStyle: { backgroundColor: '#fff' }
 });

 export default AppNavigator;

The ArticlesScreen will mount first, calling componentDidMount() , when i call this.props.navigation.navigate('Profile') inside the article screen (with a button) the navigate go to my Profile screen, calling the componentDidMount() function of my profile. When a call this.props.navigation.navigate('Articles'), the navigation go to ArticlesScreen, and not call the componentDidMount(). But when a call this.props.navigation.navigate('Profile') again the componentDidMount() function of my profile will execute, and this is generating some problems.

In resume, why when i call ProfileScreen the page is mounting by zero, and my ArticlesScreen not? And how can i fix it?

Upvotes: 0

Views: 202

Answers (1)

obai
obai

Reputation: 417

componentDidMount() will be called only when a component gets mounted. If the component is already in the navigation history, when you navigate back to it, it doesn't get mounted again. So, componentDidMount() will not be called on them.

When you navigate back to a previously mounted component, any component mounted after the one you just navigated to will be unmounted. That means, when you navigate to Articles from Profile, Profile is unmounted. That is why going back to Profile is triggering componentDidMount() again.

Understanding the Navigation lifecycle will help you here.

The Example scenario makes it more clear.

Consider a stack navigator with screens A and B. After navigating to A, its componentDidMount is called. When pushing B, its componentDidMount is also called, but A remains mounted on the stack and its componentWillUnmount is therefore not called.

When going back from B to A, componentWillUnmount of B is called, but componentDidMount of A is not because A remained mounted the whole time.

Upvotes: 1

Related Questions