美文网首页
React中组件的生命周期

React中组件的生命周期

作者: 放风筝的小小马 | 来源:发表于2017-08-22 23:30 被阅读180次

react 创造组件

// 创造组件的方式
// 方式一:使用class
// class Welcome extends React.Component {
//   render() {
//     return <h1>Hello, {this.props.name}</h1>;
//   }
// }

// 方式二:使用函数
function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}
export default Welcome

引用:

ReactDOM.render(
  <Welcome name="hexon"/>,
  document.getElementById('root')
)

记住:组件不能修改它得到的props

state

组件不能改变它得到的props,那么组件中可以变的东西放在state
注意:函数形式的组件不支持state

如何改变state

如果是直接通过给this.state赋值,是无法改变state的,必须通过this.setState来改变。

关于setState,一定要看这篇文章:setState:这个API设计到底怎么样

关于setState需要理解以下几点:

  • setState不会立刻改变React中state的值
  • 多次setState函数调用产生的效果会合并,可以理解为多次调用,只有一次生效
  • 了解函数式的setState用法

React中组件的生命周期

主要有三个阶段:mount(挂载)update(更新)unmount(移除)

mount(挂载阶段)

mount就是第一次让组件出现在页面中的过程。关键就是render()方法,React会将render()的返回值(一般是虚拟DOM、也可以是DOM或null)插入到页面中。

这个时候会暴露几个钩子函数供我们往其中添加代码,如下:

  • constructor()
  • componentWillMount()
  • render()
  • componentDidMount() :一般在该阶段进行ajax操作
    图片展示过程如下:
image.png

update(更新阶段)

mount之后,如果数据有任何变动,就会来到update过程,这个过程有5个钩子:

  • componentWillReceiveProps(nextProps) —— 已挂载的组件,在接收到新的props之前调用该函数
  • shouldComponentUpdate(nextProps, nextState) —— 询问是否要更新组件?如果返回false,则不会往下执行,终止组件更新;如果返回true,则继续往下执行,可以在该函数内添加一些判断,跳过不需要被更新的组件,提升性能
  • componentWillUpdate() —— 我要更新组件了
  • render() —— 更新
  • componentDidUpdate() —— 更新完毕了: 比较适合发送ajax到服务器端的函数,可以在该生命周期函数中对输入的新props与旧props进行比较,来决定是否发送请求到服务器端

unmount(移除阶段)

当一个组件要从页面中移除时,会进入到unmount阶段,该阶段有一个钩子函数:

  • componentWillUnmount() —— 我要被移除了

我们可以在移除之前做一些清理工作


既然React中一个组件的生命周期包含有这么三个阶段,同时,我们说要改变state只能通过setState进行修改,那么可以在哪些阶段使用setState对state进行更新呢?
一般而言,只在以下几个钩子函数中调用setState:

  • componentWillMount()
  • componentDidMount()
  • componentWillReceiveProps()
  • componentDidUpdate()
import React, { Component } from 'react';
import ReactDOM from 'react-dom';

class Number extends Component {
  constructor(props) {
    super(props);
    console.log('%c constructor 子组件已构造', 'font-weight: bolder', 'color: blue');
  }

  componentWillMount() {
    console.group('%c React挂载', 'color: #00d8ff');
    console.log('%c componentWillMount 组件即将挂载', 'font-weight:bold')  
  }
  componentDidMount() {
    console.log('%c componentDidMount 组件已挂载', 'font-weight:bold')
    console.groupEnd();
  }
  componentWillReceiveProps(newProps) {
    console.group("%c React Updating", 'color: green')
    console.log('%c componentWillReceiveProps 组件即将接收props', 'font-weight:bold', '')
    console.log('newProps', newProps.counter)
    console.log('this.props', this.props.counter)
  }
  shouldComponentUpdate(newProps, newState) {
    const result = true
    console.info(`%c shouldComponentUpdate 返回判断是否要更新组件 ${result}` , 'font-weight:bold;color: #236fd4')
    if (!result) console.groupEnd()
    return result;
  }
  componentWillUpdate(nextProps, nextState) {
    console.log('%c componentWillUpdate 组件即将更新', 'font-weight:bold', '')
    console.log('nextProps', nextProps.counter)
    console.log('this.props', this.props.counter)
  }
  componentDidUpdate(prevProps, prevState) {
    console.log('%c componentDidUpdate 组件已更新', 'font-weight:bold', '')
      console.log('prevProps', prevProps.counter)
      console.log('this.props', this.props.counter)
      console.groupEnd();
  }
  componentWillUnmount() {
    console.group("%c React Unmounting", 'color: brown')
    console.log('%c componentWillUnmount 组件即将卸载','font-weight:bold' , 'color: gray')
    console.groupEnd();
  }
  render() {
    console.log('%c render 组件渲染中...', 'font-weight:bold', '')
    console.log('this.props.counter', this.props.counter)
    return <p>{ this.props.counter }</p>
  }
 }
 
 class LifecycleCounter extends Component {
   constructor(props) {
     super(props);
     this.state = {
       counter: 0
     }
   }
   addOne() {
     this.setState((prevState) => ({
       counter: prevState.counter + 1
     }))
   }
   unMount() {
     console.info(ReactDOM.unmountComponentAtNode(document.getElementById('root')));
   }
   update() {
     this.forceUpdate();
   }
   render() {
     return (
       <div className="LifecycleCounter">
        <Number counter={this.state.counter}></Number>
        <button onClick={() => this.addOne()}>增加一</button>
        <button onClick={() => this.update()}>强制更新</button>
        <button onClick={() => this.unMount()}>卸载</button>
       </div>
     )
   }
}
export {
  LifecycleCounter
}

相关文章

  • react(最近搞了一套react项目的视频 全套 有需

    React 组件生命周期在本章节中我们将讨论 React 组件的生命周期。 组件的生命周期可分成三个状态: Mou...

  • React概念图

    React概念图 React组件生命周期概念图 参考文档:React入门教程 组件生命周期React:组件生命周期...

  • React 组件生命周期

    组件生命周期 参考阅读: component-lifecycle react组件生命周期过程说明 react 组件...

  • React总结

    [toc] 1.React组件生命周期 1.1 生命周期图 组件的生命周期的图如下: 具体可参考React 组件生...

  • React生命周期

    React生命周期 React中组件也有生命周期,也就是说也有很多钩子函数供我们使用, 组件的生命周期,我们会分为...

  • 学习并实现react (4)

    实现生命周期 生命周期介绍 React 生命周期图 React 子组件在父组件下的生命周期流程 实现 compon...

  • Notes On React - Two

    React 的生命周期   React组件 的生命周期大致可分成四个状态:  - Mounting:装配-组件实例...

  • 006@React组件的生命周期.md

    006@React组件的生命周期.md React Native 是基于组件化开发。弄清楚组件的生命周期对于我们开...

  • React学习笔记(三)-- 组件的生命周期

    摘要 React中的组件类似于状态机,每个组件都被设计成为在其生命周期过程中输出稳定、语义化的标签。React组件...

  • React 生命周期

    React 生命周期 初始化周期 组件重新渲染生命周期 组件卸载生命周期

网友评论

      本文标题:React中组件的生命周期

      本文链接:https://www.haomeiwen.com/subject/rgvtrxtx.html