Description
Custom Android back button behavior · React Navigation
At first, you may be inclined to use
componentDidMount
to subscribe for the back press event andcomponentWillUnmount
to unsubscribe. Reason why we do not use them is that they are not generally called when entering or leaving a screen.More specifically, consider a
StackNavigator
with screensA
andB
. After navigating toA
, itscomponentDidMount
is called. When pushingB
, itscomponentDidMount
is also called, butA
remains mounted and itscomponentWillUnmount
is therefore not called.Similarly, when going back from
B
toA
,componentWillUnmount
ofB
is called, butcomponentDidMount
ofA
is not becauseA
remained mounted the whole time.
This is significantly important especially when it is integrated with Redux. However, the document is placed on the improper location.
I have formed Redux states that correspond with page components one by one whose style is often adopted on the Web. But the behaviors of componentDidMount
and componentWillUnmount
on StackNavigator
are completely different from those on the Web. I finally noticed that a state of stackable screen must be kept in an array or placed as a local state of React rather than the global state of Redux, but it was too late. I wasted a lot of time. This important information should be written in a early section.