【问题标题】:React Native detect when user is trying to quit the app?React Native 检测用户何时尝试退出应用程序?
【发布时间】:2021-04-12 12:22:24
【问题描述】:

我想根据组件卸载更新我的 redux 状态,但如果用户终止应用程序,如何检测它并根据应用程序终止更新我的 redux 状态,因为在退出应用程序的情况下不会调用 componentWillUnmount .有没有办法在本机反应中检测应用程序终止(未暂停)?

【问题讨论】:

  • @RagulCs 这也是我需要回答的问题,但我也没有找到任何合适的解决方案。我会更新我的问题。
  • @3limin4t0r 我会告诉你我的用例我想在首次安装组件时显示一个模式,我在我的 redux 状态下保持它,我在 componentWillUnmount 和以及模态解雇。但是假设用户打开了组件并在此时显示了模态,用户退出了应用程序,那么下次模态将再次显示,因为它的状态没有更新。

标签: javascript reactjs react-native react-lifecycle react-lifecycle-hooks


【解决方案1】:

我猜你的困惑应该通过理解以下方法来消除:

import React from "react";
export default class Clock extends React.Component {
  constructor(props) {
    console.log("Clock", "constructor");
    super(props);   
    this.state = {
      date: new Date()
    };
  }
  tick() {   
    this.setState({
      date: new Date()
    });
  }
  // These methods are called "lifecycle hooks".
  componentDidMount() {
    console.log("Clock", "componentDidMount");
    this.timerID = setInterval(() => {
      this.tick();
    }, 1000);
  }
  // These methods are called "lifecycle hooks".
  componentWillUnmount() {
    console.log("Clock", "componentWillUnmount");
    clearInterval(this.timerID);
  }
  render() {
    return (        
        <div>It is {this.state.date.toLocaleTimeString()}.</div>
    );
  }
}

【讨论】:

  • 我了解生命周期方法在 react 和 react native 中是如何工作的,我想知道的是 react-native 而不是 react。当我们退出应用程序时,将调用 componentWillUnmount 如果没有的话有什么方法可以知道用户正在退出应用程序。
猜你喜欢
  • 2023-03-23
  • 1970-01-01
  • 2022-11-10
  • 1970-01-01
  • 2016-04-20
  • 2019-08-20
  • 2016-01-24
  • 1970-01-01
相关资源
最近更新 更多