2016-06-15 8 views
0

私は基本的なES6反応アプリを持っていて、いくつかの日付を操作するためにmomentJSを使用しようとしています。私はMoment().month()など何も動作するように思われるを使用して初期状態を設定するさまざまなバージョンを試してみました日付の操作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> 
    ) 
} 

}

:私はmonth.add is not a function

を得続ける何らかの理由で現在、私が持っているコードは、このです。どんな助けでも大歓迎です。

答えて

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

感謝を試してみてください。例えばcurrentDateのように1つのオブジェクトしか作成していないのであれば、後で 'this.state.currentDate.format(" MMMM ")'を使うことは可能でしょうか? –

+0

はい、可能です。あなたはhtmlを更新するだけです。 –

+0

現時点では、おそらく問題はありませんが、心に留めておく価値があります。 –

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