【问题标题】:React Native not running functions when leaving page离开页面时React Native没有运行功能
【发布时间】:2019-06-06 13:25:00
【问题描述】:

现在我有以下内容:

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-navigationcomponentWillUnmount() 运行但一旦saveSomething 完成,如果我不在页面上,我的警报框仍然会弹出。

有人知道为什么会这样吗?

【问题讨论】:

  • 你的渲染中是否调用了saveSomething
  • @Treycos 通过触摸动作调用它
  • 如果触摸动作完全正常,你的组件必须已经挂载
  • @Treycos 我不确定你想告诉我什么。如果我在 saveSomething 得到响应之前离开页面,我只需要找出一种方法,让 Success 警报不显示/在 isMounted if 语句之后执行任何操作。
  • 您是否担心 react 生命周期功能不起作用?自己做isMounted 跟踪有点反模式。保存信息之类的反应约定是使用 componentDidUnmount 生命周期函数。

标签: javascript react-native


【解决方案1】:

您可以使用navigation prop 的isFocused 方法来检查屏幕是否聚焦。

https://reactnavigation.org/docs/en/navigation-prop.html

【讨论】:

    【解决方案2】:

    堆栈更下方的组件可以接收对诸如 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多