我想更新每分钟的日期和时间。我已经使用了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
);
}
答案 0 :(得分:2)
您必须记住一些事情
首先:传递给useState
函数的参数仅在组件装入时使用一次
第二个:不得直接调用setInterval
内的useEffect
。
第三步:您必须注意关闭
第四次:一遍又一遍地更新具有相同值的状态不会导致重新渲染,因此始终使用setInterval中初始关闭的日期
第五步::必须清除卸载组件的间隔。
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"/>