React JS获取当前日期

Luk*_*rat 19 javascript reactjs

我想在我的componnent中输出当前日期.在控制台中我的代码可以工作,但React控制台说:

"bundle.js:14744 Uncaught RangeError:超出最大调用堆栈大小"

我的组件看起来像这样:

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>
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

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

多谢!

Ped*_*lho 24

您的问题是您正在命名组件类Date.当你new Date()在你的类中调用时,它不会创建Date你期望它创建的实例(这可能是这个Date) - 它将尝试创建组件类的实例.然后构造函数将尝试创建另一个实例,另一个实例和另一个实例......直到你用完堆栈空间并得到你看到的错误.

如果您想Date在课堂上使用,请尝试将您的课程命名为不同的类别,例如CalendarDateComponent.

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

  • 非常棒的解释+1 :) (4认同)

Mah*_*san 22

完整日期和时间:

{new Date().toLocaleString() + ""}
Run Code Online (Sandbox Code Playgroud)

仅提取月份(当前):

{new Date().toLocaleString("en-US", { month: "long" })}
Run Code Online (Sandbox Code Playgroud)

仅提取日期:

{new Date().toLocaleString("en-US", { day : '2-digit'})}
Run Code Online (Sandbox Code Playgroud)

仅提取年份:

{new Date().getFullYear()}
Run Code Online (Sandbox Code Playgroud)


Abh*_*dra 15

选项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}`
}
Run Code Online (Sandbox Code Playgroud)

并通过将其导入为使用它

import {getCurrentDate} from './utils'
console.log(getCurrentDate())
Run Code Online (Sandbox Code Playgroud)

选项 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}`
}
Run Code Online (Sandbox Code Playgroud)


小智 5

您可以使用 react-moment 包

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

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

import moment from "moment";

date_create: moment().format("DD-MM-YYYY hh:mm:ss")
Run Code Online (Sandbox Code Playgroud)


Naw*_*win 5

简单的解决方案是

{new Date().toLocaleString() + ''}
Run Code Online (Sandbox Code Playgroud)