React类组件生命周期与this关键字

类组件生命周期

参考链接
一图胜千言(不常用的生命周期函数已隐藏)
在这里插入图片描述
代码:

//CC1.js
import { Component } from "react";

export default class CC1 extends Component {
  constructor(props) {
    super(props);
    console.log("construtor");
    this.state = {
      count: 0,
    };
  }

  componentDidMount() {
    console.log("component Did Mount");
  }

  componentDidUpdate() {
    console.log("component Did Update");
  }

  increaseCount() {
    console.log("this:", this);
    this.setState((preState) => ({
      count: preState.count + 1,
    })); 
  }

  componentWillUnmount() {
    console.error("unmount");
  }
  render() {
    console.log("render");
    let { count } = this.state;
    return (
      <>
        <div>类组件一</div>
        <p>{count}</p>
        <div>
          <button onClick={this.increaseCount}>count+1</button>
        </div>
      </>
    );
  }
}
组件挂载

  组件初次挂载时,先执行构造方法中的内容,接着是render方法,最后是componentDidMount钩子;(通过打印语句可验证)

组件更新

问题:当我们点击按钮更新count时,会发现控制台报错,并没有成功使得count+1。这是因为在函数increaseCount中,this的指向丢失了。
解决问题:
(1)在构造方法中通过bind方法绑定this指向;

constructor(props) {
    super(props);
    console.log("construtor");
    this.state = {
      count: 0,
    };
    this.increaseCount = this.increaseCount.bind(this);
}

(2)将increaseCount方法改成箭头函数的形式;
参考链接

increaseCount = () => {
    console.log("this:", this);
    this.setState((preState) => ({
      count: preState.count + 1,
    }));
  };

(3)在调用increaseCount方法的时候使用bind函数绑定this指向:

<div>
     <button onClick={this.increaseCount.bind(this)}>count+1</button>
</div>

  上述三种方法解决了this指向的丢失问题。
  当我们再点击按钮就可以更新count的状态了,此时组件中函数的执行顺序是,render =》componentDidUpdate。

组件卸载

  在根组件中引入类组件,模拟组件的卸载;
代码:

//App.jsx
import { useState } from "react";
import CC1 from "./CC1";
function App() {
  const [flag, setFlag] = useState(true);
  return (
    <>
      <div>
        <div>App</div>
        <div>{flag ? <CC1 /> : ""}</div>
        <button onClick={() => setFlag(!flag)}>destory/load</button>
      </div>
    </>
  );
}

export default App;

点击按钮可模拟类组件CC1的卸载,此时函数componentWillUnmount中的代码会执行。

函数式组件

  现在官方已经推崇函数式组件,因为其比类组件简化了很多,没有烦人的this指向和那么多的生命周期函数。通过很多hooks也可以模拟组件的生命周期。
  类组件上述的众多生命周期函数,在函数式组件中只需要一个useEffect hook就可以达到一样的效果,并且代码量大大减少。
代码:

import { useEffect, useState } from "react";

export default function Fc() {
  const [count, setCount] = useState(0);
  useEffect(() => {
    console.log("count更新了");
    return () => {
      console.log("preCount", count);
    };
  }, [count]);
  const increaseCount = () => {
    setCount(count + 1);
  };
  return (
    <div>
      <div>Fc</div>
      <p>{count}</p>
      <button onClick={increaseCount}>count+1</button>
    </div>
  );
}

解释:
  useEffect钩子函数又称清理副作用的函数。
  上述的useEffect的依赖项为[count],说明函数主体内的内容会在组件初次挂载时,以及count更新时会执行,相当于类组件中的componentDidMount函数和componentDidUpdate函数。
  useEffect钩子可以返回一个函数,又称为清理函数(例如可以清理定时器等等)。这个清理函数中的代码,会在组件更新时,以及组件卸载时执行,在其中可以拿到组件更新之前或者卸载之前的状态。模拟了类组件中的componentWillUnmount函数和带参数的componentDidUpdate(可以获取上次的状态)

  • 12
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值