2016-06-15 51 views
0

我有一个基本的ES6反应的应用程序,并试图用momentJS来操纵一些日期。出于某种原因,我不断收到month.add is not a function操作日期Momentjs在ReactJS

目前我的代码是这样的:

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

当你做.format()你把它变成一个字符串,它不再是一个momentJS对象。

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个对象,例如currentDate,那么稍后可以使用'this.state.currentDate.format(“MMMM”)'? –

+0

是的,这是可能的。你只需更新html。 –

+0

是的,你可以,虽然目前的时间可能是在创建对象的时候,而不是当你做一个.format的时候 - 可能不是一个问题,但值得铭记 –

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') 
    }); 
}