首页 > 解决方案 > 如何在 react-native 中准确使用和更新全局变量?

问题描述

我是反应原生的新手。我写了秒表,但问题是当我转到另一个页面然后再次返回时,秒表停止工作。我希望秒表一直工作,直到用户按下停止按钮。我知道,我应该使用全局变量,但我不知道如何使用它。这是我的代码:

export default class Record extends Component {
 constructor(props) {
  super(props);
  this.state = {
  stopwatchStart: false,
  stopWatchTime: '00:00:00'

};
toggleStopwatch() {

if (!this.state.stopwatchStart) {
  startDate = new Date();
  startTime = startDate.getTime();
  that = this;
  setInterval(function () {
    var date = new Date();
    time = (date.getTime() - startTime) / 1000;
    hour = parseInt(time / 3600);
    timeAgo = parseInt(time % 3600);
    min = parseInt(timeAgo / 60);
    second = parseInt(timeAgo % 60);
    that.setState({
      stopWatchTime: (hour + ':' + min + ':' + second)
    })
  }, 1000);  
}
this.setState({ stopwatchStart: !this.state.stopwatchStart });}

标签: javascriptandroidreact-native

解决方案


我认为你应该使用 redux 来处理这个...... https://redux.js.org/


推荐阅读