在ReactJS中操纵日期Momentjs

时间:2016-06-15 16:31:48

标签: javascript reactjs state momentjs

我有一个基本的ES6反应应用程序,我正在尝试使用momentJS来操纵一些日期。出于某种原因,我不断获得month.add is not a function

目前我的代码是:

export default class CalendarApp extends React.Component {

constructor() {
    super();

    this.state = {
        currentDate: Moment().format(),
        month: Moment().format('MMMM'),
        year: Moment().format('YYYY')
    }

    // Bind Methods to this
    this.previousMonth = this.previousMonth.bind(this);
    this.nextMonth = this.nextMonth.bind(this);
}

previousMonth() {
    let month = this.state.month;
    month.add(-1, 'months');
    this.setState({
        month: month
    })
}

nextMonth() {
    let month = this.state.month;
    month.add(1, 'months');
    this.setState({
        month: month
    })
}

render() {
    return (
        <div className="calendar">
            <div className="calendar-container" style={ hideCalendar }>
                <caption>
                    <button className="previous-month" onClick={ this.previousMonth }>Prev</button>
                    <button className="next-month" onClick={ this.nextMonth }>Next</button> 
                    <div className="calendar-month">
                        <span>{ this.state.month } { this.state.year }</span>
                    </div>
                </caption>
            </div>
        </div>
    )
}

}

我已尝试使用Moment().month()等设置初始状态的各种版本,但似乎没有任何效果。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:3)

当你.format()将它变成一个字符串时,它不再是一个时刻.JS对象。

moment().add(1, 'months') // A moment object

moment().add(1, 'months').subtract(6, 'days') // Can still manipulate

moment().add(1, 'months').subtract(6, 'days').format() // A final string, can't call moment funcs on it

如果他们全部使用相同的时间,也不需要创建多个对象 -

const momentNow = Moment();

this.state = {
  currentDate: momentNow.format(),
  month: momentNow.format('MMMM'),
  year: momentNow.format('YYYY')
}

答案 1 :(得分:1)

你的state.month是一个字符串。这导致了这个问题。

试试这个

constructor() {
    super();

    this.state = {
        currentDate: Moment(),
        month: Moment().format('MMMM'),
        year: Moment().format('YYYY')
    }

    // Bind Methods to this
    this.previousMonth = this.previousMonth.bind(this);
    this.nextMonth = this.nextMonth.bind(this);
}

previousMonth() {
    let date = this.state.currentDate;
    date.add(-1, 'months');
    this.setState({
        currentDate: date,
        month: date.format('MMMM'),
        year: date.format('YYYY')
    });
}

nextMonth() {
    let date = this.state.currentDate;
    date.add(1, 'months');
    this.setState({
        currentDate: date,
        month: date.format('MMMM'),
        year: date.format('YYYY')
    });
}
相关问题