gpt4 book ai didi

javascript - 我如何制作一个计时器?

转载 作者:行者123 更新时间:2023-12-02 21:05:27 25 4
gpt4 key购买 nike

我想计算用户使用我的应用程序的时间,例如,当我的 React Native iOS 应用程序进入前台时。然后,一旦它移到后台,我想捕获它在前台的秒数(然后将其发送到分析,但这是另一项任务)。这是我到目前为止正在做的事情,但它说它“无法读取未定义的属性“第二个””。我怎样才能达到这个结果?

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

}


}

最佳答案

只需将 this 绑定(bind)到构造函数中的函数或使用如下箭头函数:

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

关于javascript - 我如何制作一个计时器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61237088/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com