admin管理员组

文章数量:1426491

When I try to use a date from Moment.js in the constructor, ponentWillMount, or ponentDidMount, I get the error:

Uncaught TypeError: _moment2.default.date is not a function

I am not using Webpack or any specific build tool outside of npm. Here is my relevant code:

import React from 'react';
import Moment from 'moment';

export default class Date extends React.Component {
  constructor() {
    super();
    this.state = { day: '',
                   month: '',
                   year: '',
                   weekday: ''
                 };
  }

  ponentDidMount() {
    this.setDate();
  }

  setDate() {
    this.state.day = Moment.date();
    this.state.month = Moment.format('MMM');
    this.state.year = Moment.year();
    this.state.weekday = Moment.format('dddd');
  }

Is this because Moment hasn't fully been loaded when the ponent is rendered, or is it something else? How can I get this fixed?

When I call Moment just in the render() function, I don't get this error. But, I need the date information in the state so that I can update other app ponents based on the date.

When I try to use a date from Moment.js in the constructor, ponentWillMount, or ponentDidMount, I get the error:

Uncaught TypeError: _moment2.default.date is not a function

I am not using Webpack or any specific build tool outside of npm. Here is my relevant code:

import React from 'react';
import Moment from 'moment';

export default class Date extends React.Component {
  constructor() {
    super();
    this.state = { day: '',
                   month: '',
                   year: '',
                   weekday: ''
                 };
  }

  ponentDidMount() {
    this.setDate();
  }

  setDate() {
    this.state.day = Moment.date();
    this.state.month = Moment.format('MMM');
    this.state.year = Moment.year();
    this.state.weekday = Moment.format('dddd');
  }

Is this because Moment hasn't fully been loaded when the ponent is rendered, or is it something else? How can I get this fixed?

When I call Moment just in the render() function, I don't get this error. But, I need the date information in the state so that I can update other app ponents based on the date.

Share Improve this question asked Feb 9, 2017 at 20:02 CassidyCassidy 3,3655 gold badges41 silver badges80 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 5

Way you are setting the state is not proper, and use Moment like this: Moment()., try this:

setDate() {
      this.setState({
           day : Moment().date(),
           month : Moment().format('MMM'),
           year : Moment().year(),
           weekday : Moment().format('dddd')
      });
  }

本文标签: javascriptUncaught TypeError moment2defaultdate is not a function in React appStack Overflow