LoginSignup
0
0

More than 3 years have passed since last update.

【React⑤】State

Last updated at Posted at 2020-10-22

Stateとは

  • コンポネント内で状態を管理する変数(Local State)
  • Reactではコンポネントの内部で状態を保つことができる
  • Propsは親コンポネントから値を渡されたのに対してStateはコンポネントの内部でのみ使用される
  • Propsは変更不可(immutable)に対してStateは変更可能(mutable)
  • StateはClass Componentで使う

propsについては以下参照
https://qiita.com/suema0331/private/ba7b0bd5521571df0c49

  • Propsとはコンポネントの属性、あるデータの属性で参照できるもののこと
  • {}で囲って渡していく
  • 受けわたせるデータ型は文字列、数値、真偽、配列、オブジェクト、変数などなんでも可能

Stateを使う理由

  • render()内部では値を変更してはいけない
    →renderするとstateが変わって再レンダーされてまたstate変わって再レンダー∞💥😇
  • setState()で値を変更する
  • stateの変更が起こると再レンダーする
    →そのためページリロードせずDOMが変わるので表示を切り替えられる

Stateの使い方

  • Class Componentのconstructor()内で以下のように宣言
  • オブジェクト型で書く
  • 取得時には同じコンポネント内ではthis.state.keyで取得可能
  • 子コンポネントとして参照したいときはpropsとして渡す
  • renderのなかでtoggle = {this.togglePublished()}のように渡すと関数が実行されてしまう!
    →関数がtoggleで呼び出された時に実行されるようにする必要

setStateでStateを変更する

  • 関数にラップして使う
  • setState()内に記述されたstateのみ変更
  • 複数のstateを設定した場合でも、isPublishedのみ変更される
    togglePublished = () =>{
        this.setState( {isPublished: !this.state.isPublished})
    };

※注:下のように直接初期化したstateを変更してはいけない
状態を変え、DOMも更新したいので、setStateを使うことで状態を変えた時に自動でrenderが実行される。

this.setState({count: this.state.count +1 })
//this.state = {count: this.state.count +1 } NG!!!

renderの内で関数をtoggleで呼び出された時に実行されるようにする例
Article.jsxonClickprops.toggle関数を呼び出した時に
toggleというpropsを関数で渡す。

Blog.jsx
import React from 'React';

class Blog extends React.Component{
    constructor(props){
        super(props);
        this.state ={
            isPublished:false,
            order=1
        }
    }

    togglePublished = () =>{
        this.setState( {isPublished: !this.state.isPublished})
    };

    render(){
        return(
            <>
                <Article title={"React"} 
                        isPublished={this.state.isPublished}
                        //toggleというpropsを関数で渡す必要
                        toggle = {() => this.togglePublished()}
                />  
            </>
        )
    }
}

export default Blog
Article.jsx
import React from 'React';

//公開状態のcheckbox
//onClickでprops.toggle関数を呼び出す

const Article = (props) =>{
    return(
        <div>
            <h2>{props.title}</h2>
            <label htmlFor="check">公開状態: </label>
            <input type="checkbox" checked={props.isPublished} id="check" onClick={() => props.toggle()}/>
        </div>
    )
};

export default Article

setStateを使ってカウントボタン作成

  • this.state={count:0}初期化時にstate宣言
  • handlePlusButtonメソッドの中でstateを変更
import React, {Component} from 'react';

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

class Counter extends Component {
 constructor(props){    //初期化処理で実行されるメソッド
  super(props)          //親クラスで初期化処理を行う
  this.state={count:0}  //オブジェクトがstateに設定される
 }

  handlePlusButton = () => { //handlePlusButtonメソッドの中でstateの値を+1する
    this.setState({count: this.state.count +1 })//状態を変更するメソッド}

handleMinusButton = () => {
    this.setState({count: this.state.count -1 })
}

 render (){  //render関数を呼んでreturnのなかでcounter文字列を返す
  return(    //returnするJSXは一個でないといけない
  <React.Fragment>  
     <div>count: {this.state.count }</div>
     <button onClick={this.handlePlusButton}>+1</button>  
     <button onClick={this.handleMinusButton}>-1</button>  
  </React.Fragment>
  )
}
}
export default App;
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0