如何在 React 中修复'TypeError: moment is not a function'?



我曾尝试降级到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 => {

将函数更改为

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

未经测试,但应该有效。

最新更新