React Class 组件学习(二)

372 阅读2分钟

生命周期
Lifecycle

生命周期

  • 类比如下代码
let div = doucument.creatElement('div')
//这是div的create/construc过程
div.textContent = 'hi'
//这是初始化state
document.body.appendChild(div)
//这是div的mount过程
div.textContent = 'h2'
//这是div的update过程
div.remove()
//这是div的unmount过程
  • 同理
    React组件也有这些过程,我们称之为生命周期
React中的生命周期
  • 函数列表 constructor()

static getDerivedStateFromProps()

shouldComponentUpdate()

render()

getSnapshotBeforeUpdate()

componentDidMount()

componentDidUpdate()

componentWillUnmount()

static getDerivedStateFromError()

componentDidCatch()

要求掌握的生命周期
  • 函数列表 constructor()-在这里初始化state

shouldComponentUpdate()-return false阻止更新

render()-创建虚拟DOM

componentDidMount()-组件已出现在页面

componentDidUpdate()-组件已更新

componentWillUnmount()-组件将死

constructor
  • 用途
    初始化props
    初始化state,但此时不能调用setState
    可不写 用来写bind this
constructor(){
    /* 其他代码略 */
    this.onClick = this.onClick.bind(this)
}

可以用新语法代替

onClick = ()=>{}
constructor(){/* 其他代码略*/}
shouldComponentUpdate
  • 用途
    返回true表示不阻止UI更新
    返回false表示阻止UI更新
    示例见下页
  • 面试常问
    问: shouldComponentUpdate有什么用?
    答: 它允许我们手动判断是否要进行组件更新,我们可以根据应用场景灵活地设置返回值,以避免不必要的更新
示例代码
class App extends React.Component {
   constructor(props) {
     super(props);
     this.state = {
       n: 1
      };
    }
    onClick = () => {
       this.setState(state => ({n: state.n + 1}));
       this.setState(state => ({n: state.n - 1}));
     };
     shouldComponentUpdate(newProps, newState){
        if(newState.n === this.state.n){
           return false
          }else{
              return true
          }
        }
        render() {
           console.log('render 了一次')
           return (
              <div>
                 {this.state.n}
                 <button onClick={this.onClick}>+1-1</button>
               </div>
            );  
          }
        }
  • 启发
    为什么React不内置此功能?
    React确实内置了
    这个功能叫做 React.PureComponent 可以代替React.Component
render
  • 用途
    展示视图
    return(
    ...
    )
    只能有一个根元素
    如果有两个根元素,就要用<React.Fragment>包起
    <React.Frggment/>可以缩写成<></>
  • 技巧
    render里面可以写if...else
    render里面可以写 ? : 表达式
    render里面不能直接写for循环,需要用数组
    render里面可以写array.map(循环)
componentDidMount()
  • 用途
    在元素插入页面后执行代码,这些代码依赖DOM
    比如你想获取div的高度,就最好在这里写
    此处可以发起加载数据的AJAX请求(官方推荐)
    首次渲染会执行此钩子
  • 参数
    看文档
componentDidUPdate()
  • 用途
    在视图更新后执行代码
    此处也可以发起AJAX请求,用于更新数据(看文档)
    首次渲染不会执行此钩子
    在此处setState可能会引起无限循环,除非放在if里
    若shouldCOmponentUpdate返回false,则不会除发此钩子
  • 参数
    看文档
componentWillUnmount
  • 用途
    组件将要被移除页面然后被销毁时执行代码
    unmount过的组件不会再次mount
  • 举例
    如果你在componentDidMount里面监听了window scroll
    那么你就要在componentWillUnmount 里面取消监听
    如果你在componentDidMount里面创建了Timer
    那么你就要在componentWillUnmount 里面取消Timer
    如果你在conmponentDidMount里面创建了AJAX请求
    那么你就要在componentWillUnmount 里面取消请求

分阶段看钩子执行顺序

微信截图_20210814143222.png

本文为fjl的原创文章,著作权归本人和饥人谷所有,转载务必注明来源