React Class Component 生命週期 - Mounting 篇

挑战 React 第二十一篇

主要分成以下四大类:

MountingUpdatingUnmountingError Handling

Mounting

Mounting 生命週期

Mounting 有四个生命週期

Constructor

初始化 state事件绑定

static getDerivedStateFromProps(nextProps, prevState)
自己没用过这个方法,但官网表示:

是一个 static 静态函数,因此无法操作 class 中的属性 (ex. this.state)无条件的根据 prop 更新内部 state,也就是只要有传入prop 值, 就更新state只有 prop 和 state 不同时才更新 state

render()

回传 React Element

componentDidMount

取的 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 官方网站连结


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章