Javascript React JS 获取当前日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43744312/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:08:10  来源:igfitidea点击:

React JS get current date

javascriptreactjs

提问by Lukas Niestrat

I want to output the current date in my componnent. In the console my code works, but the React console says:

我想在我的组件中输出当前日期。在控制台中,我的代码有效,但 React 控制台显示:

"bundle.js:14744 Uncaught RangeError: Maximum call stack size exceeded"

“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>
        );
    }
}

Yeah, I know I'm a pretty beginner, but maybe someone can help me. I googled for hours -.-

是的,我知道我是一个很好的初学者,但也许有人可以帮助我。我用谷歌搜索了几个小时-.-

Thx alot!

多谢!

回答by Pedro Castilho

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 Dateyou 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。当您new Date()在您的类中调用时,它不会创建Date您期望它创建的实例(很可能是thisDate)-它会尝试创建您的组件类的实例。然后构造函数将尝试创建另一个实例,另一个实例,另一个实例......直到你用完堆栈空间并得到你看到的错误。

If you want to use Datewithin your class, try naming your class something different such as Calendaror DateComponent.

如果您想Date在您的班级中使用,请尝试将您的班级命名为不同的名称,例如CalendarDateComponent

The reason for this is how JavaScript deals with name scope: Whenever you create a new 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 Datewithin a class named Date, the name Datewill refer to that class and not to any object named Datewhich existed before the class definition started.

这样做的原因是 JavaScript 处理名称范围的方式:每当您创建一个新的命名实体时,如果在范围内已经有一个具有该名称的实体,该名称将停止引用前一个实体并开始引用您的新实体。因此,如果您在名为Date的类中使用名称Date,则该名称Date将引用该类,而不是Date在类定义开始之前存在的任何命名对象。

回答by Abhinav Chandra

OPTION 1: if you want to make a common utility function then you can use this

选项1:如果你想制作一个通用的实用功能,那么你可以使用这个

export function getCurrentDate(separator=''){

let newDate = new Date()
let date = newDate.getDate();
let month = newDate.getMonth() + 1;
let year = newDate.getFullYear();

return `${year}${separator}${month<10?`0${month}`:`${month}`}${separator}${date}`
}

and use it by just importing it as

并通过将其导入为使用它

import {getCurrentDate} from './utils'
console.log(getCurrentDate())

OPTION 2: or define and use in a class directly

选项 2: 或直接在类中定义和使用

getCurrentDate(separator=''){

let newDate = new Date()
let date = newDate.getDate();
let month = newDate.getMonth() + 1;
let year = newDate.getFullYear();

return `${year}${separator}${month<10?`0${month}`:`${month}`}${separator}${date}`
}

回答by Andrés Alejandro Benítez

You can use the react-moment package

您可以使用 react-moment 包

-> https://www.npmjs.com/package/react-moment

-> https://www.npmjs.com/package/react-moment

Put in your file the next line:

在您的文件中放入下一行:

import moment from "moment";

date_create: moment().format("DD-MM-YYYY hh:mm:ss")