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.
- 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;