ReactNavigation 生命周期
ReactNavigation 生命周期
官网的描述
In a previous section, we worked with a stack navigator that has two screens (Home and Details) and learned how to use navigation.navigate(‘RouteName’) to navigate between the routes.
An important question in this context is: what happens with Home when we navigate away from it, or when we come back to it? How does a route find out that a user is leaving it or coming back to it?
If you are coming to react-navigation from a web background, you may assume that when user navigates from route A to route B, A will unmount (its componentWillUnmount is called) and A will mount again when user comes back to it. While these React lifecycle methods are still valid and are used in react-navigation, their usage differs from the web. This is driven by more complex needs of mobile navigation.
简单来说就是,你设置了两个页面A和B,如果用了React的生命周期函数componentDidMount,A页面一开始会调用这个函数,但是路由导航到了B页面时再回到A页面时,生命周期函数则就不再触发了
做案例的时候遇到了这个问题,需求是通过路由跳转到其他页面修改数九,回到页面数据重新刷新,从而让页面保持数据保持最新状态。
再官网翻阅资料后发现,官方给出的方法是监视路由的变化来进行 导航事件
导航事件
通过给navigation添加监听事件,第一个参数是事件类型,第二个参数是这个事件的回调函数,此函数会返回一个可以取消监听的函数
const aa = navigation.addListener('tabPress', e => {
// Prevent default action
e.preventDefault();
});
aa(); // 取消监听
事件类型参数:
- focus
- blur
- state
- tabPress
回调函数的三个形参:
- data
- target
- preventDefault
具体用法看官网
更多推荐



所有评论(0)