`componentDidMount()` function is not called after navigation

北城以北 提交于 2019-11-27 16:04:56

问题


I am using stackNavigator for navigating between screens. I am calling two API's in componentDidMount() function in my second activity. When i load it first time, it gets loaded successfully. Then i press back button to go back to first activity. Then, if i am again going to second activity, the APIs are not called and I get render error. I am not able to find any solution for this. Any suggestions would be appreciated.


回答1:


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.




回答2:


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()
}



回答3:


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.




回答4:


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();



回答5:


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 .



来源:https://stackoverflow.com/questions/48018084/componentdidmount-function-is-not-called-after-navigation

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