【发布时间】:2021-02-08 22:24:55
【问题描述】:
我的 React App 组件中有一个 javascript Time 函数,一切运行良好。但主要问题是我需要几秒钟的时间来继续计数,而不是在页面刷新之前保持静止。
已经尝试了几次,但仍然无法正常工作。下面附上我目前所拥有的。
我的代码在下面。
App.js
import React, { Component } from 'react'
export class App extends Component {
constructor(props) {
super(props)
this.state = {
}
}
render() {
function getDateTime() {
let now = new Date();
let year = now.getFullYear();
let month = now.getMonth()+1;
let day = now.getDate();
let hour = now.getHours();
let minute = now.getMinutes();
let second = now.getSeconds();
if(month.toString().length === 1) {
month = '0'+month;
}
if(day.toString().length === 1) {
day = '0'+day;
}
if(hour.toString().length === 1) {
hour = '0'+hour;
}
if(minute.toString().length === 1) {
minute = '0'+minute;
}
if(second.toString().length === 1) {
second = '0'+second;
}
var dateTime = hour+':'+minute+':'+second;
return dateTime;
}
return(
<div>
{<h2>The time is {getDateTime()}</h2>}
</div>
)}
}
export default App
索引.js
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
const rootElement = document.getElementById("root");
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
rootElement
);
【问题讨论】:
-
这里的想法是将时间存储在
state中,并在每次您希望计时器更新时更新状态。
标签: javascript html reactjs react-native