React JS获取当前日期 [英] React JS get current date
问题描述
我想在组件中输出当前日期.在控制台中,我的代码有效,但是React控制台显示:
I want to output the current date in my componnent. In the console my code works, but the React console says:
"bundle.js:14744未捕获的RangeError:超出了最大调用堆栈大小"
我的组件看起来像这样:
My component looks like that:
import React from 'react';
var FontAwesome = require('react-fontawesome');
export class Date extends React.Component {
constructor() {
super();
var today = new Date(),
date = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate();
this.state = {
date: date
};
}
render() {
return (
<div className='date'>
<FontAwesome name='calendar' />{this.state.date}
</div>
);
}
}
是的,我知道我是一个漂亮的初学者,但也许有人可以帮助我.我用Google搜索了几个小时-.-
Yeah, I know I'm a pretty beginner, but maybe someone can help me. I googled for hours -.-
很多!
推荐答案
您的问题是您正在命名组件类 Date
.当您在类中调用 new Date()
时,它不会创建您希望创建的 Date
的实例(可能是
Your problem is that you are naming your component class Date
. When you call new Date()
within your class, it won't create an instance of the Date
you expect it to create (which is likely this Date
)- it will try to create an instance of your component class. Then the constructor will try to create another instance, and another instance, and another instance... Until you run out of stack space and get the error you're seeing.
如果您想在班级中使用 Date
,请尝试为班级命名不同的名称,例如 Calendar
或 DateComponent
.
If you want to use Date
within your class, try naming your class something different such as Calendar
or DateComponent
.
原因是JavaScript处理名称范围的方式:每当创建新命名的实体时,如果在范围内已经存在具有该名称的实体,则该名称将停止引用先前的实体,并开始引用您的新实体.因此,如果您在名为 Date
的类中使用名称 Date
,则名称 Date
将引用该类,而不引用任何名为的对象>日期
(在类定义开始之前存在).
The reason for this is how JavaScript deals with name scope: Whenever you create a newly named entity if there is already an entity with that name in scope, that name will stop referring to the previous entity and start referring to your new entity. So if you use the name Date
within a class named Date
, the name Date
will refer to that class and not to any object named Date
which existed before the class definition started.
这篇关于React JS获取当前日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!