【问题标题】:Problem using NPM Moment.js in React: moment__WEBPACK_IMPORTED_MODULE_2__format is not a function?在 React 中使用 NPM Moment.js 出现问题:moment__WEBPACK_IMPORTED_MODULE_2__format 不是函数?
【发布时间】:2019-07-20 15:39:18
【问题描述】:

编辑:我现在使用 dateFns (date-fns.org) 解决了我的问题,但我也很想知道如何在这里使用 Momentjs。

我使用create-react-app 创建了一个应用程序,并尝试使用某种格式将当前数据转换为字符串。但是,我收到以下错误

moment__WEBPACK_IMPORTED_MODULE_2__format 不是函数

当我尝试运行这段代码时

import moment from 'moment'

 const today = moment().calendar().format('DD-MM-YYY')
 const tomorrow = moment().add(1, 'days').calendar().format('DD-MM-YYY')
 this.setState({checkin:today,checkout:tomorrow})

我做了一些谷歌搜索,发现了像 https://github.com/moment/moment/issues/4229 这样的页面,其中一个建议是尝试

import * as moment from 'moment'

但这也无济于事。

我也试过

import * as moment from 'moment/moment'

这是另一个建议,但也没有用。

即使只是打电话

moment.format('DD-MM-YYY')

抛出同样的错误。

我的package.json 有这些依赖项

"dependencies": {
    "moment": "^2.24.0",
    "react": "^16.8.6",
    "react-datetime": "^2.16.3",
    "react-dom": "^16.8.6",
    "react-scripts": "3.0.1"
  },

我不知道如何前进。非常感谢任何帮助!

【问题讨论】:

  • 尝试安装 react-moment

标签: javascript node.js reactjs webpack momentjs


【解决方案1】:

试试这个:

 const today = moment(moment().calendar()).format('DD-MM-YYY')
 const tomorrow = moment(moment().add(1, 'days').calendar()).format('DD-MM-YYY')

我假设.calender() 将返回一个string,如果我们需要将其解析为特定格式,我们需要将其作为param 传递给另一个moment然后将format 应用到它。

【讨论】:

    猜你喜欢
    • 2021-05-24
    • 1970-01-01
    • 2019-01-21
    • 1970-01-01
    • 1970-01-01
    • 2021-05-13
    • 2020-11-28
    • 1970-01-01
    • 2019-03-25
    相关资源
    最近更新 更多