React中组件的生命周期

2017-08-22  本文已影响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需要理解以下几点:


React中组件的生命周期

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

mount(挂载阶段)

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

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

image.png

update(更新阶段)

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


unmount(移除阶段)

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

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


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

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
}
上一篇下一篇

猜你喜欢

热点阅读