我有以下秒表实现
import { useState, useEffect } from 'react';
import { Text, View, StyleSheet, Button } from 'react-native';
function TimerComponent() {
const [isActive, setIsActive] = useState(false);
const [time, setTime] = useState(0);
useEffect(() => {
let interval = null;
if (isActive) {
interval = setInterval(() => {
setTime(time => time + 0.1);
}, 100);
} else {
clearInterval(interval);
}
return () => {
clearInterval(interval);
};
}, [isActive]);
const handleStart = () => {
setIsActive(true);
};
const handleReset = () => {
setIsActive(false);
setTime(0);
};
const roundedTime = time.toFixed(1);
return (
<View style={styles.outerContainer}>
<Button
title="Start"
onPress={handleStart}
/>
<Text style={styles.text}>{roundedTime}</Text>
<Button
title="Stop"
onPress={handleReset}
/>
</View>
);
}
export default TimerComponent;
在 Android 上,它按预期工作,当我与另一个秒表比较时,它同时达到 30 秒,但当我在 iOS 上测试时,它需要大约 5 秒的时间。
不要使用
setTime(time => time + 0.1);
来计算经过的时间。
而是使用Date
:
const start = Date.now();
console.log('starting timer...');
// Expected output: "starting timer..."
setTimeout(() => {
const millis = Date.now() - start;
console.log(`seconds elapsed = ${Math.floor(millis / 1000)}`);
// Expected output: "seconds elapsed = 2"
}, 2000);