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

时间:2021-04-12 12:22:24

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

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

1 个答案:

答案 0 :(得分:0)

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

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