加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 20:43:39 所属栏目:百科 来源:网络整理
导读:当我想在屏幕打开时做一些动作时,我把它们放在componentDidMount中.例如,我可以获取一些数据. 像这样. componentDidMount() { this.updateData();} 但是反应导航componentDidMount只在用户第一次打开屏幕时出现一次,如果以后用户再次打开此页面则不会触发com
当我想在屏幕打开时做一些动作时,我把它们放在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',};

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读