React ライフサイクメソッドについて
Reactで、元データは、propsであったり、APIで取得してきて、setStateをするケースが多多あると思います。
初期データは、ライフサイクルメソッドで設定する場合が多いと思います。
呼び出すタイミングによっては、データがstateに正しくセットされずに表示されないなどが結構あるので、 よく使いそうなメソッドを動かして理解する為にまとめました。
ライフサイクルメソッドとは?
Reactのrenderされるまでの手順だと思っている
ちゃんと言葉を理解したい人は他の人の記事で
よく使いそうなライフサイクルメソッド
- componentWillMount
renderメソッドが呼ばれる前に実行される
componentWillMount() { }
- componentDidMount
renderメソッドが呼ばれた後に実行される
componentDidMount() { }
- componentDidUpdate
stateが更新された後に実行される
componentDidUpdate() { }
検証
class App extends Component { constructor(props){ super(props) this.state = { lists: [1,2,3,4,5] } } componentWillMount() { console.log("call componentWillMount") } componentDidMount() { console.log("call componentDidMount") } componentDidUpdate() { console.log("call componentDidUpdate()") } render () { console.log("call render()") return (<div>{this.state.lists.map((li) => <li key={li}>{li}</li>)}</div>) } } export default App;
このソースの場合、 componentWillMount() => render() => componentDidMount()の順番
stateを更新してみる
class App extends Component { constructor(props){ super(props) this.state = { lists: [1,2,3,4,5] } } componentWillMount() { console.log("call componentWillMount") } componentDidMount() { console.log("call componentDidMount") const newList = Object.assign([], this.state.lists) newList.splice(2,1) this.setState({lists: newList }) } componentDidUpdate() { console.log("call componentDidUpdate()") } render () { console.log("call render()") return (<div>{this.state.lists.map((li) => <li key={li}>{li}</li>)}</div>) } } export default App;
componentDidUpdate()が呼ばれました。 componentDidUpdate()前のrender()が2回呼ばれている理由がわかりませんが、 なんとなくライフサイクルメソッドが体感で分かった気がする。
APIなどで、componentWillMount とcomponentDidlMountどちらに初期データを呼べばいいの?
とりあえず動作の検証
- componentWillMountにデータをセットする
class App extends Component { constructor(props){ super(props) this.state = { lists: [] } } componentWillMount() { this.setState({lists: [1,2,3,4,5] }) } componentDidMount() { }
- componentDidMountにデータをセットする
class App extends Component { constructor(props){ super(props) this.state = { lists: [] } } componentWillMount() { } componentDidMount() { this.setState({lists: [1,2,3,4,5] }) }
んん。。どっちが良いのだろうか