react-native – react-navigation:检测屏幕,tabbar激活/出现/焦点/模糊

前端之家收集整理的这篇文章主要介绍了react-native – react-navigation:检测屏幕,tabbar激活/出现/焦点/模糊前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
当我想在屏幕打开时做一些动作时,我把它们放在componentDidMount中.例如,我可以获取一些数据.

像这样.

componentDidMount() {
  this.updateData();
}

但是反应导航componentDidMount只在用户第一次打开屏幕时出现一次,如果以后用户再次打开此页面则不会触发componentDidMount.

检测页面(屏幕)何时被激活并执行操作的正确方法是什么?

使用react-navigation,您可以做到这一点.

>在componentDidMountor componentWillMount中添加侦听器

this.subs = [
  this.props.navigation.addListener('didFocus',(payload) => this.componentDidFocus(payload)),];

要么

this.subs = [
  this.props.navigation.addListener('didFocus',this.componentDidFocus),this.props.navigation.addListener('willBlur',this.componentWillBlur),];

然后你可以在componentDidFocus中做任何事情,比如获取数据,更新数据,……
>在componentWillUnmount中,删除侦听器

componentWillUnmount() {
  this.subs.forEach(sub => sub.remove());
}

有关更多详细信息,请参阅此PR:https://github.com/react-navigation/react-navigation/pull/3345

更新:

addListener – Subscribe to updates to navigation lifecycle

React Navigation emits events to screen components that subscribe to
them:

  • willBlur – the screen will be unfocused

  • willFocus – the screen will focus

  • didFocus – the screen focused (if there was a transition,the
    transition completed)

  • didBlur – the screen unfocused (if there was a transition,the
    transition completed)

参考:https://reactnavigation.org/docs/en/navigation-prop.html#addlistener-subscribe-to-updates-to-navigation-lifecycle

更新示例:

const didBlurSubscription = this.props.navigation.addListener(
  'didBlur',payload => {
    console.debug('didBlur',payload);
  }
);

JSON有效负载

{
  action: { type: 'Navigation/COMPLETE_TRANSITION',key: 'StackRouterRoot' },context: 'id-1518521010538-2:Navigation/COMPLETE_TRANSITION_Root',lastState: undefined,state: undefined,type: 'didBlur',};

猜你在找的React相关文章