javascript - Display updated time each seconds in react function
问题描述
It must be a function, it can't be a class (class is able to do it in the componentDidMount with setInterval)
I set up something like this
function DisplayTime() {
let time = new Date().getTime();
setInterval(() => {
time = new Date().getTime();
}, 1000);
return time;
}
ReactDOM.render(<DisplayTime />, document.getElementById('root'))
The problem is function can run only once, so the time won't able to get update. Something like setInterval(() => {ReactDOM.render(...), ...})
low efficient, which is not acceptable.
Any idea?
===
useState is advanced solution, any solution without using most recent version of React?
解决方案
import React, { useState } from "react";
import ReactDOM from "react-dom";
import "./styles.css";
function App() {
const [time, setTime] = useState(new Date().getTime());
setInterval(() => {
setTime(new Date().getTime());
}, 1000);
return (
<div className="App">
<h1>{time}</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
推荐阅读
- javascript - 如何在 Html 中验证数据?
- angular - 反应式表单控件触发更改检测
- sql - 如何在行上添加或更新数据但不会重复具有两个相同值的同一行的项目
- excel - 根据分数在班级之间分配学生
- javascript - 错误:尝试使用 jquery 显示 HTML 响应时显示 [$rootScope:infdig] 10 $digest() 迭代次数
- python - 查找某一行中的值以特定字符串开头的索引 - AttributeError: 'DataFrame' object has no attribute 'ix'
- c - 如何修复 c 声明但未引用或从未引用的编译器错误
- javascript - 如何删除我的待办事项应用程序上的项目?
- image - 我想在 github 存储库中显示图像供人们查看
- javascript - SplideJS全角图像滑块不自动播放