LoginSignup
0
0

More than 3 years have passed since last update.

【React⑥】ライフサイクルで主要なメソッド

Last updated at Posted at 2020-10-22

ライフサイクルとは

  • コンポネントが生まれてから死ぬまでの時間の流れ(データやviewの変更など)
  • 各段階で、必要な処理をライフサイクルメソッドで記述
    • Mounting:コンポネントが配置される期間(URLにアクセスした時)
    • Updating:コンポネントが変更される期間(画面クリック、データの操作を行った時)
    • Unmounting:コンポネントが破棄される期間(画面を閉じた時)

ライフサイクルの必要性

*関数の外に影響を与える関数を記述するため(DOM変更、API通信、ログ出力、、)
*副作用のある処理を記述する(適切な場所に配置すべき処理)ことができる

ライフサイクルメソッド

lifecycle.png

  • Mounting

    • constructor():stateなどを初期化。コンポネントの中で初めから使いたいものを宣言
    • render():バーチャルDOMを描画する。JSXをリターンする。
    • componentDidMount():render後に1度だけ呼ばれてイベントリスナー設定やAPI通信に使う
  • Updating

    • render():VDOMを再描画
    • componentDidMount():再レンダー後に呼ばれる。(スクロールイベントでコンポネント表示など)
  • Unmounting

    • componentWillUnmount():コンポネント破棄直前にリソースを開放、リスナーの解除など

ボタンがクリックされるといいねをカウントの実装

イベントリスナーでArtucle.jsxid={"counter"}のボタンに対してclickした時にcountUp関数を呼ぶ。
この時countUp()で渡すとrender無限ループになってしまうので関数型で書くか、関数名のみ渡してあげる。

Blog.jsx
import React from 'React';
import Article from "./Article";

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

    componentDidMount(){
        document.getElementById('counter').addEventListener('click', this.countUp)
    }

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

    //呼び出されたらcountのstateを変更
    countUp = () => {
         this.setState( {count: this.state.count + 1})
    }


    render(){
        return(
            <>
                <Article 
                        title={"React"} 
                        isPublished={this.state.isPublished}
                        toggle = {() => this.togglePublished()}
                        count={this.state.count}
                />  
            </>
        )
    }
}

export default Blog
Article.jsx
const Article = (props) =>{
    return(
        <div>
            <h2>{props.title}</h2>
            <label htmlFor="check">公開状態: </label>
            <input type="checkbox" checked={props.isPublished} id="check" onClick={() => props.toggle()}/>
            <LikeButton count={props.count} />
        </div>
    )
};
Likebutton.jsx
import React from 'React';

//関数名はファイル名と合わせる
const LikeButton = () =>{
    return(
        <button id={"counter"}>いいね数:{props.count}</button>
    )
}

export default LikeButton

stateを更新・リスナー設定を解除

//いいね数が10超えたら0に戻す
componentDidUpdate(){
    if (this.state.count >= 10){
        this.setState({count:0})
    }
}

リスナーを解除しておくとサーバの負荷が減る。

componentWillUnmount(){
    document.getElementById('counter').addEventListener('click', this.countUp)
}
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