挑战 React 第二十一篇
主要分成以下四大类:
MountingUpdatingUnmountingError HandlingMounting
Mounting 生命週期
Mounting 有四个生命週期
Constructor
初始化 state事件绑定static getDerivedStateFromProps(nextProps, prevState)
自己没用过这个方法,但官网表示:
render()
回传 React ElementcomponentDidMount
取的 API 资料使用 setState()实际範例
利用 console.log() 印出生命週期
import React, { Component } from 'react';class LifeCycle extends Component { constructor(props) { super(props); this.state = { test: 'aaaa', } console.log('Constructor'); } static getDerivedStateFromProps(nextProps, prevState) { console.log('getDerivedStateFromProps'); // 回传 null 表示 state 无异动 return null; } componentDidMount() { console.log('componentDidMount'); } render() { console.log('render'); return ( <div> LifeCycle Test </div> ) }}export default LifeCycle;
网页呈现
有 Child Componet 的範例
import React, { Component } from 'react';import ChildLifeCycle from './ChildLifeCycle';class ParentLifeCycle extends Component { constructor(props) { super(props); this.state = { test: 'aaaa', } console.log('Parent Constructor'); } static getDerivedStateFromProps(nextProps, prevState) { console.log('Parent getDerivedStateFromProps'); // 回传 null 表示 state 无异动 return null; } componentDidMount() { console.log('Parent componentDidMount'); } render() { console.log('Parent render'); return ( <div> Parent LifeCycle <ChildLifeCycle /> </div> ) }}export default ParentLifeCycle
import React, { Component } from 'react';class ChildLifeCycle extends Component { constructor(props) { super(props); this.state = { test: 'aaaa', } console.log('Child Constructor'); } static getDerivedStateFromProps(nextProps, prevState) { console.log('Child getDerivedStateFromProps'); // 回传 null 表示 state 无异动 return null; } componentDidMount() { console.log('Child componentDidMount'); } render() { console.log('Child render'); return ( <div> Child LifeCycle </div> ) }}export default ChildLifeCycle;
网页呈现
参考 React 官方网站连结