`componentDidMount()` function is not called after navigation

大城市里の小女人 提交于 2019-11-29 04:26:24

If anyone coming here in 2019, try this:

import {NavigationEvents} from 'react-navigation';

Add the component to your render:

<NavigationEvents onDidFocus={() => console.log('I am triggered')} />

Now, this onDidFocus event will be triggered every time when the page comes to focus despite coming from goBack() or navigate.

If the upvoted syntax that uses NavigationEvents component is not working, you can try with this:

// no need to import anything more

// define a separate function to get triggered on focus
onFocusFunction = () => {
  // do some stuff on every screen focus
}

// add a focus listener onDidMount
async componentDidMount () {
  this.focusListener = this.props.navigation.addListener('didFocus', () => {
    this.onFocusFunction()
  })
}

// and don't forget to remove the listener
componentWillUnmount () {
  this.focusListener.remove()
}

React-navigation keeps the component mounted even if you navigate between screens. You can use the component to react to those events :

<NavigationEvents
  onDidFocus={() => console.log('hello world')}
/>

More info about this component here.

In React, componentDidMount is called only when component is mounted.I think what you are trying to do is call your API on going back in StackNavigator. You can pass a callback function as parameter when you call navigate like this on Parent Screen:

  navigate("Screen", {
     onNavigateBack: this.handleOnNavigateBack
  }); 
  handleOnNavigateBack = () => {//do something};

And on Child Screen

this.props.navigation.state.params.onNavigateBack();
this.props.navigation.goBack();

You want to perform something after every time navigating to a component using drawernavigator or stacknavigator ; for this purpose NavigationEvents fits better than componentDidMount .

import {NavigationEvents} from "react-navigation";
<NavigationEvents onDidFocus={()=>alert("Hello, I'm focused!")} />

Note : If you want to do the task every time after focusing on a component using drawer navigation or stack navigation then using NavigationEvents is better idea. But if you want to do the task once then you need to use componenetDidMount .

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!