React Native 检测用户何时尝试退出应用程序?

问题描述

我想根据组件卸载更新我的 redux 状态,但如果用户终止应用程序如何检测并根据应用程序终止更新我的 redux 状态,因为在退出应用程序的情况下将不会调用 componentwillUnmount .有没有办法在 React Native 中检测应用程序终止(未挂起)?

解决方法

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

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>
    );
  }
}