【问题标题】:Uncaught TypeError: _moment2.default.date is not a function in React app未捕获的 TypeError:_moment2.default.date 不是 React 应用程序中的函数
【发布时间】:2017-06-28 00:02:21
【问题描述】:

当我尝试在构造函数、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 时,我没有收到此错误。但是,我需要状态中的日期信息,以便我可以根据日期更新其他应用程序组件。

【问题讨论】:

    标签: javascript reactjs momentjs


    【解决方案1】:

    您设置状态的方式不正确,并像这样使用 Moment:Moment().,试试这个:

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

    【讨论】:

    • 多哈。谢谢你。注意,您在此答案中使用了 = 而不是 :。 :)
    猜你喜欢
    • 2018-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-05
    • 2017-05-15
    • 2020-04-15
    • 1970-01-01
    相关资源
    最近更新 更多