我想计算用户在我的应用程序上停留的时间,例如,当我的反应原生 iOS 应用程序进入前台时。然后,一旦它移到后台,我想捕获它在前台的秒数(然后将其发送到分析,但这是另一项任务)。到目前为止,这就是我正在做的事情,但它说的是它'cannot read property 'second' of undefined'。我如何达到这个结果?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)    }  }}
                    
                    
                1 回答
 
                    
                    
                            德玛西亚99
                            
                                
                            
                        
                        
                                                
                    TA贡献1770条经验 获得超3个赞
只需在构造函数中绑定this到您的函数或使用如下箭头函数:
this.onAppStateChange = this.onAppStateChange.bind(this)
or onAppStateChange = () => {
//your code
}
添加回答
举报
0/150
	提交
		取消
	