How to trigger an event when a component is shown when using react-native-navigation?
I like the solution proposed by Bruno Reis. I tweaked mine to make it a bit simpler.
class Whatever extends Component {
componentDidMount(){
this.load()
this.props.navigation.addListener('willFocus', this.load)
}
load = () => {
...
}
}
include this as 'callIfBackToThisRoute'...
export default ( props, call ) => {
if( !props.navigation ) throw 'I need props.navigation'
const thisRoute = props.navigation.state.routeName;
props.navigation.addListener(
'willFocus',
payload => {
if( payload.state.routeName == thisRoute) call(props)
}
);
}
and use it inside your component...
componentDidMount() {
const { doIt } = this.props;
doIt()
callIfBackToThisRoute(
this.props,
(props) => doIt()
)
}
For RNN v3, after trying out for quite a couple times, I finally figured out the correct way:
componentDidMount() {
this.navigationEventListener = Navigation.events().bindComponent(this);
}
componentWillUnmount() {
if (this.navigationEventListener) {
this.navigationEventListener.remove();
}
}
componentDidAppear() { // Lazy loading data for RNN
if (this.state.routes.length === 0) {
this.getData();
}
}
The key is that, the binding of event listener is mandatory, otherwise the componentDidAppear() and componentDidDisappear() won't be triggered.