简体   繁体   English

我如何制作计时器?

[英]How do i make a timer?

I'd like to time how long a user has been on my app, so for example, when my react native iOS app moves in to the foreground.我想计算用户使用我的应用程序的时间,例如,当我的反应原生 iOS 应用程序进入前台时。 Then as soon as it moves to the background, i would like to capture the number of seconds it was in the foreground for (and then send it to analytics, but that's another task).然后,一旦它移到后台,我想捕获它在前台的秒数(然后将其发送到分析,但这是另一项任务)。 Here's what i'm doing so far, but it its saying that it 'cannot read property 'second' of undefined' .到目前为止,这是我正在做的事情,但它说它'cannot read property 'second' of undefined' How do i achieve this result?我如何达到这个结果?

class Home extends Component {

  constructor(props) {
      super(props)

      this.state = {

        second: 0
      }
  }

 componentDidMount = async () => {

    AppState.addEventListener('change', this.onAppStateChange) 
 }

  //Tracks when app is brought to foreground or background
  onAppStateChange(appState) {    
    if(appState === 'active') {   
      //User is ON App 
      console.log('ON');

      this.timer = setInterval(() => {
        this.setState ({ second: this.state.second + 1 }) },
        1000
      )

    }
    if(appState === 'background') {
      //User is OFF App
      console.log('OFF');
      clearInterval(this.timer);
      console.log(this.state.second)
    }

  }


}

Just Bind this to your function in the constructor or use arrow function like this:只需在构造函数中将其绑定this您的 function 或使用箭头 function ,如下所示:

this.onAppStateChange = this.onAppStateChange.bind(this)
or onAppStateChange = () => {
  //your code
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM