如何解决如何计算特定屏幕用户在React Native上花费的时间
我正在尝试计算用户打开特定屏幕时的时间,当他进入屏幕时,时间开始,而当我从屏幕退出时,时间停止并给出在屏幕上花费的时间
这是我的代码:
componentDidMount = () => {
let date = new Date();
let hours = date.getHours();
let minutes = date.getMinutes();
let seconds = date.getSeconds();
this.setState({
startHour: hours,startMin: minutes,startSeconds: seconds,});
}
这是Componentwillunmount
componentwillUnmount() {
let date = new Date();
let endHours = date.getHours();
let endMinutes = date.getMinutes();
let endSeconds = date.getSeconds();
console.log(`${endHours}:${endMinutes}:${endSeconds}`);
console.log(
`${this.state.startHour}:${this.state.startMin}:${this.state.startSeconds}`,);
}
解决方法
我不是React开发人员,但这相当简单,这就是方法。
componentDidMount = () => {
/* On init set the start time
Also: multiplying new Date() by 1 will return a timestamp
*/
this.startTime = new Date() * 1;
}
componentWillUnmount() {
/* Then on view destroy set the endTime */
let endTime = new Date() * 1;
/* Subtract the end time with start time,since endTime has greater value. The result
is the difference between start and end time in milliseconds.
*/
let elapsed = endTime - this.startTime;
/* The result is in milliseconds so:
elapsed / 1000 -> is seconds
elapsed / 1000 / 60 -> is minutes
etc.
*/
);
,
看这段代码,这是一个功能组件。
import React,{ useState,useEffect } from 'react';
export const Chronometer = () => {
const [time,setTime] = useState({
seconds: 0,minutes: 0,hours: 0,});
useEffect(() => {
let isCancelled = false;
const advanceTime = () => {
setTimeout(() => {
let nSeconds = time.seconds;
let nMinutes = time.minutes;
let nHours = time.hours;
nSeconds++;
if (nSeconds > 59) {
nMinutes++;
nSeconds = 0;
}
if (nMinutes > 59) {
nHours++;
nMinutes = 0;
}
if (nHours > 24) {
nHours = 0;
}
!isCancelled && setTime({ seconds: nSeconds,minutes: nMinutes,hours: nHours });
},1000);
};
advanceTime();
return () => {
//final time:
console.log(time);
isCancelled = true;
};
},[time]);
return (
<div>
<p>
{`
${time.hours < 10 ? '0' + time.hours : time.hours} :
${time.minutes < 10 ? '0' + time.minutes : time.minutes} :
${time.seconds < 10 ? '0' + time.seconds : time.seconds}
`}
</p>
</div>
);
};
要显示useEffect挂钩中的总时间,您可以返回一个函数,在此示例中,我使用console.log,但是如果要将其传递给其他组件,则可以提升状态或将其传递给网址参数
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。