Perviously when I wanted to make some actions when screen is opened I put them inside componentDidMount. For example I can fetch some data.
like this.
componentDidMount() {
this.updateData();
}
But with react-navigation componentDidMount occurs only one time when user open screen first time, and if later user open this page again it will not trigger componentDidMount.
What is proper way to detect when page(screen) is activated and do actions?
componentDidMount
/componentWillUnmount
does not work in all cases of navigation (like tabs).You need to use
addListener
with events didFocus and didBlur to make such actions. See documentation for detailsWith
react-navigation
, you can do that.Add listeners in
componentDidMount
orcomponentWillMount
or
Then you can do anything in
componentDidFocus
, like fetching data, updating data,...In
componentWillUnmount
, remove listenersFor more detail, see this PR: https://github.com/react-navigation/react-navigation/pull/3345
Updated:
Ref: https://reactnavigation.org/docs/en/navigation-prop.html#addlistener-subscribe-to-updates-to-navigation-lifecycle
Updated example:
JSON payload:
Perhaps try componentDidUpdate and set a state within your component. When the state changes the re-render occurs