我正在构建一个具有秒表功能的网络应用程序,我正确开发了它,但没有存储数据(本地存储)。所以,当用户重新加载并关闭它时,它会从0开始。
我想将这个时间数据保留在“本地存储”中,这样当用户关闭或重新加载网站时它就不会从0开始。
我将这些秒表功能保留在 useStopwatch 挂钩中。
"use client";
import { useState } from "react";
export default function useStopwatch() {
const [days, setDays] = useState(0);
const [hrs, setHrs] = useState(0);
const [mins, setMins] = useState(0);
const [secs, setSecs] = useState(0);
const [progressTime, setProgressTime] = useState(0);
const [intervalId, setIntervalId] = useState<NodeJS.Timeout | undefined>();
let startTime = 0;
let elapsedTime = 0;
const start = () => {
startTime = Date.now() - elapsedTime;
const id = setInterval(updateTime, 1000);
setIntervalId(id);
};
const restart = () => {
clearInterval(intervalId);
setDays(0);
setHrs(0);
setMins(0);
setSecs(0);
startTime = 0;
elapsedTime = 0;
start();
};
const updateTime = () => {
elapsedTime = Date.now() - startTime;
const secs = Math.floor((elapsedTime / 1000) % 60);
const mins = Math.floor((elapsedTime / (1000 * 60)) % 60);
const hrs = Math.floor((elapsedTime / (1000 * 60 * 60)) % 60);
const days = Math.floor(elapsedTime / (1000 * 60 * 60 * 24));
setDays(days);
setHrs(hrs);
setMins(mins);
setSecs(secs);
setProgressTime(elapsedTime);
};
return { days, hrs, mins, secs, progressTime, start, restart };
}
GitHub 存储库中的相同代码:https://github.com/rakibul-wdp/quit-zina/blob/main/hooks/useStopwatch.ts
完整项目代码:https://github.com/rakibul-wdp/quit-zina
如何为这个秒表实现“本地存储”功能?
使用这个就可以实现。
"use client";
import { useState } from "react";
export default function useStopwatch() {
const [days, setDays] = useState(0);
const [hrs, setHrs] = useState(0);
const [mins, setMins] = useState(0);
const [secs, setSecs] = useState(0);
const [progressTime, setProgressTime] = useState(0);
const [intervalId, setIntervalId] = useState<NodeJS.Timeout | undefined>();
const start = () => {
const elapsedTime = JSON.parse(localStorage.getItem("elapsedTime"));
localStorage.setItem("startTime", `${Date.now() - elapsedTime}`)
const id = setInterval(updateTime, 1000);
setIntervalId(id);
};
const restart = () => {
clearInterval(intervalId);
setDays(0);
setHrs(0);
setMins(0);
setSecs(0);
startTime = 0;
elapsedTime = 0;
start();
};
const updateTime = () => {
const startTime = JSON.parse(localStorage.getItem("startTime"));
const elapsedTime = Date.now() - startTime;
localStorage.setItem("elapsedTime", `${elapsedTime}`);
const secs = Math.floor((elapsedTime / 1000) % 60);
const mins = Math.floor((elapsedTime / (1000 * 60)) % 60);
const hrs = Math.floor((elapsedTime / (1000 * 60 * 60)) % 60);
const days = Math.floor(elapsedTime / (1000 * 60 * 60 * 24));
setDays(days);
setHrs(hrs);
setMins(mins);
setSecs(secs);
setProgressTime(elapsedTime);
};
return { days, hrs, mins, secs, progressTime, start, restart };
}