React中组件的生命周期

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
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容