LoginSignup
0
0

More than 3 years have passed since last update.

Reactを学んだ(2) ~Lifecycle Events~

Last updated at Posted at 2020-11-28

Lifecycle Events

  • 以下のようなものたちがある。
  • componentDidMount is only called once in the lifecycle of any component, re-render will not reinitialize the component. componentDidUpdate is triggered after re-rendering DOM.

image.png

  • API Callをしたい時には、componentDidMount()ライフサイクルメソッド内で行い、それによって得られたデータの変更をstateに反映させる。
  • これによって、render()メソッドはレンダリングだけが責務になるし、まずstateは最新ではないものがコンテンツの枠組みを最初に表示することができる

  • 以下のような感じ。

import React, { Component } from 'react';
import fetchUser from '../utils/UserAPI';

class User extends Component {
 constructor(props) {
   super(props);

   this.state = {
     name: '',
     age: ''
   };
 }

 componentDidMount() {
   fetchUser().then((user) => this.setState({
     name: user.name,
     age: user.age
   }));
 }

 render() {
   return (
     <div>
       <p>Name: {this.state.name}</p>
       <p>Age: {this.state.age}</p>
     </div>
   );
   }
}

export default User;
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