在React应用程序中,Uncaught TypeError: _moment2.default.date不是一个函数。

8

当我尝试在构造函数、componentWillMount 或 componentDidMount 中使用 Moment.js 的日期时,会出现以下错误:

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

我没有使用Webpack或任何特定的构建工具,只是使用npm。这是我的相关代码:

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

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

  componentDidMount() {
    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');
  }

这是因为组件被渲染时 Moment 没有完全加载,还是其他原因?我该如何修复?
当我在 render() 函数中调用 Moment 时,没有出现这个错误。但是,我需要在状态中获取日期信息,以便根据日期更新其他应用程序组件。
1个回答

5

您设置状态的方式不正确,并且使用 Moment 的方式也不对:Moment().,请尝试以下方法:

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

1
抱歉,你在这个答案中使用了=而不是:。请注意。 - Cassidy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接