javascript - 离开页面时 React Native 不运行函数

标签 javascript react-native

现在我有以下内容:

componentWillUnmount() { console.log("Leaving"); this._isMounted = false; }
componentDidMount() { this._isMounted = true; }

我有一个像这样的函数:

this.saveSomething(this.state.data).then((response) => {

  if(response !== null) {

    console.log(this._isMounted);

    if(this._isMounted) {
      Alert.alert(
        'Success!', 'It was saved',
        [
          {text: 'Go Home', style: 'cancel', onPress: () => {
            //navigate the app home
            this.props.navigation.navigate('Home');
          }},
          {text: 'Stay Here'},
          {text: 'Do something else', onPress: () => {
            //stuff that they need to be on the page to do
          }}
        ]
      );
    }
  }
})

如果此函数运行并且我使用 react-navigation 单击后退按钮,则 componentWillUnmount() 运行,但一旦 saveSomething 完成,如果我不在页面上,我的警报框仍然会弹出。

有谁知道为什么会发生这种情况吗?

最佳答案

堆栈中更靠下的组件可以接收对 componentWillReceiveProps 等方法的调用,并在未显示时进行渲染。

我认为最好的方法是在 componentDidMount 中处理 isMounted 并添加一个导航监听器,例如 didBlur,它在屏幕未聚焦时触发:

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

并确保您删除了 componentWillUnmount 内的监听器。

在此处阅读有关导航生命周期的更多信息:https://reactnavigation.org/docs/en/navigation-prop.html#addlistener-subscribe-to-updates-to-navigation-lifecycle

关于javascript - 离开页面时 React Native 不运行函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54149626/

相关文章:

javascript - 总计 Jquery 汇总

javascript - 悬停时删除 clipPath

reactjs - 如何在React Native应用程序中订阅Supabase的实时数据?

ios - Xcode 12 - 没有要编译的架构(ONLY_ACTIVE_ARCH=YES,active arch=x86_64,VALID_ARCHS=arm64e armv7s arm64 arm7)

node.js - React Native 找不到模块

Firebase Once() 超时

javascript - 有一个按钮来控制时间线 GSAP 动态 - 定位增量计数器

javascript - 理解 javascript 中的 XHR 请求对象...(困惑)

javascript - 将按键和焦点事件附加到 contenteditable div 内的元素

ios - React Native MapView 未在 iOS 独立构建上显示