[React Native]componentWillUnmount没有调用

417 阅读1分钟

用 React Navigation 进行页面跳转的时候 componentWillUnmount 没有调用到

React Navigation 版本

3.x 解决方法 订阅导航栏生命周期的更新

willFocus - 屏幕将聚焦
didFocus - 屏幕聚焦(如果有过渡,过渡完成)
willBlur - 屏幕将失去焦点
didBlur - 屏幕未聚焦(如果有过渡,则过渡完成)

示例

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

// 完成后删除侦听器
didBlurSubscription.remove();

payload 内容

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

isFocused快速获取屏幕焦点状态

let isFocused = this.props.navigation.isFocused();

官方文档地址