【问题标题】:How to fix 'TypeError: moment is not a function' in React?如何修复 React 中的“TypeError:moment is not a function”?
【发布时间】:2021-07-27 21:36:03
【问题描述】:

我已尝试降级到 Moment.js 版本 2.24.0,但这并没有解决我的问题。下面是我的代码。有什么我做错了吗?错误指向我的 formatDate 函数,但我似乎无法确定问题所在。

import moment from 'moment';

class ViewMorePhotos extends Component {
    state = {
        date: moment(),
        photo: ""
    };
    
    formatDate = moment => {
        let year = moment().year();
        let month = moment().month() + 1;
        let day = moment().date();
        return `${year}-${month}-${day}`;
    };
    
    changeDate = dateFromInput => {
        this.setState({ date: dateFromInput });
        this.getPhoto(this.formatDate(dateFromInput));
    };

    getPhoto = date => {
        fetch( `api-url`)
            .then(response => response.json())
            .then(photoData => this.setState({ photo: photoData }));
    };
    
    render() {
        return (
            <React.Fragment>
                <NavBar />
                <DateInput changeDate={this.changeDate} date={this.state.date} />
                <Photo photo={this.state.photo} />
            </React.Fragment>
        );
    }
}

这是我收到的错误:

TypeError: moment is not a function
ViewMorePhotos/this.formatDate
src/components/ViewMorePhotos.js:17

  14 | };
  15 | 
  16 | formatDate = moment => {
> 17 |     let year = moment().year();
     | ^  18 |     let month = moment().month() + 1;
  19 |     let day = moment().date();
  20 |     return `${year}-${month}-${day}`;

ViewMorePhotos/this.changeDate
src/components/ViewMorePhotos.js:25

  22 | 
  23 | changeDate = dateFromInput => {
  24 |     this.setState({ date: dateFromInput });
> 25 |     this.getPhoto(this.formatDate(dateFromInput));
     | ^  26 | };
  27 | 
  28 | getPhoto = date => {

【问题讨论】:

  • 您是否使用 npm 安装了时刻? momentjs.com/docs/#/use-it/node-js
  • 是的,我做到了!它显示在我的 package.json 中
  • 看起来您将 dateFromInput 作为参数传递给 formatDate 函数,然后将其作为函数调用。
  • @jsdev 这可能不是答案。 package.json 中的依赖关系很好,但可能仍需要再次安装。 (特别是如果版本已更改)
  • 能否分享一下代码中哪里抛出了错误?

标签: javascript reactjs api momentjs typeerror


【解决方案1】:

把你的函数改成

formatDate = aDate => {
    let m = moment(aDate)
    let year = m.year();
    let month = m.month() + 1;
    let day = m.date();
    return `${year}-${month}-${day}`;
};

未经测试,但应该可以工作。

【讨论】:

  • 太棒了!非常感谢!
猜你喜欢
  • 1970-01-01
  • 2019-09-25
  • 2019-04-05
  • 2021-10-26
  • 1970-01-01
  • 2021-10-07
  • 1970-01-01
  • 1970-01-01
  • 2020-03-26
相关资源
最近更新 更多