[英]date and time are not getting updated using setInterval in hooks
I want to update the date and time for each and every minute. 我想更新每一分钟的日期和时间。 I have used setinterval for that, but i cant able to update the time using react hooks.
我为此使用了setinterval,但是我无法使用react挂钩来更新时间。
const Link = (props) => {
let date = new Date();
const [dateTime, setDateTime] = useState({ curTime: date.toLocaleDateString(),
timeStr: date.toLocaleTimeString().replace(/:\d{2}\s/, " "),
curDay: date.toLocaleDateString("en-US", { weekday: "short" })
});
setInterval(() => {
setDateTime({
curTime: date.toLocaleDateString(),
timeStr: date.toLocaleTimeString().replace(/:\d{2}\s/, " "),
curDay: date.toLocaleDateString("en-US", { weekday: "short" })
});
console.log(dateTime);
},
60000
);
}
You must remember a few things 你必须记住一些事情
First: The parameters passed to the useState
function are used only once whenthe component mounts 第一:传递给
useState
函数的参数仅在组件安装时使用一次
Second: setInterval
must not be called directly but within useEffect
. 第二:
setInterval
不能直接在useEffect
。
Third: You must take care of closures 第三:您必须注意关闭
Fourth: State update with the same value over and over again will not cause re-renders and hence use the date from the initial closure in setInterval always 第四:重复更新具有相同值的状态不会导致重新渲染,因此始终使用setInterval中初始关闭的日期
Fifth: You must clear the interval when the component is unmounted. 第五:卸载组件时,必须清除间隔。
const Link = (props) => { let date = new Date(); const [dateTime, setDateTime] = React.useState({ curTime: date.toLocaleDateString(), timeStr: date.toLocaleTimeString().replace(/:\\d{2}\\s/, " "), curDay: date.toLocaleDateString("en-US", { weekday: "short" }) }); React.useEffect(() => { const interval = setInterval(() => { const date = new Date(); setDateTime({ curTime: date.toLocaleDateString(), timeStr: date.toLocaleTimeString().replace(/:\\d{2}\\s/, " "), curDay: date.toLocaleDateString("en-US", { weekday: "short" }) }); console.log(dateTime); }, 60000 ); return () => { clearInterval(interval)} }, []) const {curTime, timeStr, curDay} = dateTime; return ( <div> <div>CurTime: {curTime}</div> <div>TimeStr: {timeStr}</div> <div>CurDay: {curDay}</div> </div> ) } ReactDOM.render(<Link />, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script> <div id="app"/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.