Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
102 views
in Technique[技术] by (71.8m points)

javascript - React JS get current date

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

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

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!

question from:https://stackoverflow.com/questions/43744312/react-js-get-current-date

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

If you want to use Date within your class, try naming your class something different such as Calendar or DateComponent.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...