且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

React JS获取当前日期

更新时间:2023-01-27 12:14:16

您的问题是您正在命名组件类 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.