Javascript 如何使用状态在 React.js 中显示日期?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/50568107/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to display date in React.js using state?
提问by Leon Bogod
I'm trying to display date using React.js but for some reason it's not displaying anything.
我正在尝试使用 React.js 显示日期,但由于某种原因它没有显示任何内容。
I'm a beginner so I'm sorry if I'm asking a stupid question, but I can't figure out why it's not working. Can someone please help me? Thanks so much!
我是初学者,所以如果我问了一个愚蠢的问题,我很抱歉,但我不知道为什么它不起作用。有人可以帮帮我吗?非常感谢!
class App extends React.Component {
state = {
date: ""
};
getDate() {
var date = { currentTime: new Date().toLocaleString() };
this.setState({
date: date
});
}
render() {
return (
<div class="date">
<p> ddd {this.state.date}</p>
</div>
);
}
}
export default App;
回答by Carl Edwards
You're trying to get the state of the date without explicitly setting it first. With that in mind call the getDate()method in something like, ComponentDidMount:
您试图在没有先明确设置的情况下获取日期的状态。考虑到这一点,请以getDate()类似ComponentDidMount的方式调用该方法:
class App extends App.Component {
...
componentDidMount() {
this.getDate();
}
...
}
From there you should be able to retreive it in your render call:
从那里你应该能够在你的渲染调用中检索它:
render() {
return (
<div class="date">
<p> ddd {this.state.date}</p>
</div>
);
}
Update:
更新:
constructor()is probably more suitable for this situation as no external requests are called to retrieve said data:
constructor()可能更适合这种情况,因为没有调用外部请求来检索所述数据:
constructor(props) {
super(props);
this.state = {
date: new Date().toLocaleString()
};
}
回答by Martín Zaragoza
Try doing:
尝试做:
var date = new Date();
this.setState({ date });
instead of
代替
var date = {currentTime: (new Date()).toLocaleString()}
this.setState({date:date });
And check if the current date shows up.
并检查当前日期是否出现。
Then check out how to alter the date field with some format.
然后查看如何使用某种格式更改日期字段。
Hope this helps you out
希望这可以帮助你
回答by V Soren
I would suggest looking up component lifecycle methods.
我建议查找组件生命周期方法。
The state hasn't been set because you never call getDate(), so you're just getting an empty string.
状态尚未设置,因为您从未调用过 getDate(),因此您只是得到一个空字符串。
import React from "react";
export default class App extends React.Component {
state = {
date: ""
};
componentDidMount() {
this.getDate();
}
getDate = () => {
var date = new Date().toDateString();
this.setState({ date });
};
render() {
const { date } = this.state;
return <div>{date}</div>;
}
}
回答by nurealam siddiq
Here's a simple way:
这是一个简单的方法:
class App extends React.Component {
state = {date: new Date()}
render() {
return (
<div class="date">
<p> ddd {this.state.date.toLocaleDateString()}</p>
</div>
);
}
}
export default App;
Cheers!
干杯!

