react 事始め 6

◾️State

ReactのComponentでは、Componentの内部で状態をもつことができる。内部の状態をStateという。

PropsとStateの違い

  • Propsは親のComponentから値を渡されたのに対して、StateはComponentの内部でのみ使用される。
  • Propsは変更不可能(immutable)な値、Stateは変更可能(mutable)な値

Stateは、Class Componentで使用できる機能である。

import React, { Component } from 'react';

const App = () => (<Counter></Counter>)

class Counter extends Component {
  constructor(props){
    super(props)
    this.state = { count: 0 }
  }
  render(){
    return ( <div>count: { this.state.count }</div> )
  }
}

export default App;

constructorは、初期化処理を実行するメソッド。Counterが呼び出された時、Counterクラスのインスタンスが作成される。 その際にconstructorメソッドが呼び出される。その初期化時の状態に対してオブジェクトが設定される(this.state = { count: 0 })。 この後、renderメソッドが呼び出され、その中のdivの要素の描画する部分が実行されてcount: { this.state.count }が表示される。