Which lifecycle event is called when a screen appears?

跟風遠走 提交于 2019-12-12 10:57:10

问题


Suppose I have two screens:

  • Screen A
  • Screen B

I am initially landed on Screen A. When I click on a Button I navigate to Screen B. When I press Back Button, I am again navigated to Screen A.

I want to call an action creator when I am navigated to Screen A as mentioned in above scenario.

I just want to know that which lifecycle event will be called every time when a screen is presented.

Isn't there some event like componentWillAppear()?

Note: I am using react-native with react-navigation for navigation.


回答1:


This can now be done with plain react navigation via their listeners:

In your Component A:

componentDidMount = () => {
  this._componentFocused();

  this._sub = this.props.navigation.addListener(
    'didFocus',
    this._componentFocused
  );
}

componentWillUnmount() {
  this._sub.remove();
}

_componentFocused = () => {
  this.setState({dataToShow});
}

React Navigation docs - Lifecycle




回答2:


If you use react-native-navigation, you can listen for appearance events: https://wix.github.io/react-native-navigation/#/screen-api?id=listen-to-visibility-events-globally




回答3:


When you navigate from one screen to another, the first screen will not be unmounted, but still on the stack, just hide in the background.

What you need might be componentDidFocus, but it's currently in design not avaiable yet, see react-native open issue #51.

You can try this alternative way: react-navigation-addons. With this you can have events focus & blur which may suit your needs.



来源:https://stackoverflow.com/questions/47627663/which-lifecycle-event-is-called-when-a-screen-appears

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