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 中的高阶组件主要是对于 hooks 之前的类组件来说的,如...
我们上一节了解了组件的更新机制,但是只是停留在表层上,例...
我们上一节了解了 react 的虚拟 dom 的格式,如何把虚拟 dom...
react 本身提供了克隆组件的方法,但是平时开发中可能很少使...
mobx 是一个简单可扩展的状态管理库,中文官网链接。小编在接...
我们在平常的开发中不可避免的会有很多列表渲染逻辑,在 pc ...