MENU

React クラスライフサイクルメソッド 実行順番

クラスライフサイクルメソッド 実行順番

結構この順番を理解していないと、レンダリングされる順番を理解していないと、 修正がうまく反映されないことがあるので、とても役に立ちそう

実行順番は下記らしい

1.constructor()

2. getDerivedStateFromProps(props,state)

3. render()

4. render Child Component

5. componentDidMount()

試しにconsole.logで検証

import React from 'react';
import './App.css';
import { Container,Row, Col } from 'react-bootstrap';


class Persons extends React.Component{
  constructor(props) {
    super(props)
  }

  render(){
    console.log("child component")
    return(
      <div>
        {this.props.persons.map((person) => <div key={person.id}>{person.name}</div>)}
      </div>
    )
  }
}

class App extends React.Component {
  constructor(props) {
    super(props)
    console.log("coustructor")
  }

  state = {
    persons: [
      {id:1, name:"name1"},
      {id:2, name:"name2"},
    ]
  }

  static getDerivedStateFromProps(props, state) {
    console.log("getDerivedStateFromProps ", props)
    return state
  }
  

  render () {
    console.log("render")
    return (
      <div className="App">
       <div className="container">
        <Persons persons={this.state.persons}/>
       </div>
      </div>
    );
  }
}

export default App;

キャプチャー

f:id:everydayProguramming:20200718152541p:plain

参考

www.udemy.com