Cas*_*ams 7 javascript momentjs reactjs
当我尝试在构造函数,componentWillMount或componentDidMount中使用Moment.js中的日期时,我收到错误:
Uncaught TypeError: _moment2.default.date is not a function
Run Code Online (Sandbox Code Playgroud)
我没有在npm之外使用Webpack或任何特定的构建工具.这是我的相关代码:
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');
}
Run Code Online (Sandbox Code Playgroud)
这是因为Moment在渲染组件时还没有完全加载,或者是其他什么东西?我怎样才能解决这个问题?
当我在render()函数中调用Moment时,我没有收到此错误.但是,我需要状态中的日期信息,以便我可以根据日期更新其他应用程序组件.
您设置状态的方式不正确,请使用Moment像这样:Moment().,请尝试以下操作:
setDate() {
this.setState({
day : Moment().date(),
month : Moment().format('MMM'),
year : Moment().year(),
weekday : Moment().format('dddd')
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2177 次 |
| 最近记录: |