React类组件中常见钩子函数

本文详细介绍了React组件的生命周期方法,包括构造函数constructor、渲染方法render、挂载后执行的componentDidMount等关键方法,并解释了它们的作用及使用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

constructor()

用于初始化state,如果不用初始化state,则可以省略constructor

class App extends React.PureComponent{
    constructor(props) {
        super(props);
        this.state={x:1}
    }
   }
render()

用于渲染视图

  1. render中可以使用if和三元表达式,不能使用for循环,由于for循环不是表达式。可以使用map代替for循环
  2. render中的返回值只能由一个根元素,否则必须要用<React.Fragment></React.Fragment>(可以简写为<></>)包裹起来
class App extends React.PureComponent {
    render() {
        return (
            <div>
                App
            </div>
        )
    }
}
componentDidMount()

在元素插入页面后执行的函数,首次渲染就会执行此钩子

  1. 此时可以设置定时器和发送AJAX请求,然后在componentWillUnmount()清除,否则会造成内存负担
class App extends React.Component {
    componentDidMount() {
        this.timerID = setInterval(
          () => this.tick(),
          1000
        );
      }
}
shouldComponentUpdate()

用于设置组件是否进行更新,true表示不阻止UI更新,false表示阻止UI更新

  1. 可以被React.PureComponent代替,和shouldComponentUpdate不一样的地方就是它会对比state中每一个的key,如果key有一个不一样,就会更新
class App extends React.Component {
    shouldComponentUpdate(nextProps, nextState, nextContext) {
        if (this.state.x === nextState.x) {
            return false
        } else {
            return true;
        }
    } 
}
//相当于
class App extends React.PureComponent {
}
componentDidUpdate()

在视图更新后执行函数

  1. 此处不能使用setState,如果没有做if限制的话,可能会进入死循环
  2. 如果shouldComponentUpdate的返回值为false,那么此钩子也不会执行
class App extends React.Component {
    componentDidUpdate(){
        console.log('我是componentDidUpdate')
    }
}
componentWillUnmount()

组件要被移除页面时执行的函数

  1. 被unmount之后的代码,不会重新mount
  2. 应用于消除计时器,Ajax请求,取消监听(销毁后不消除,就会占用内存)
class App extends React.Component {
  componentWillUnmount() {
    clearInterval(this.timerID);
  }
}
钩子函数的执行顺序
  1. 首次渲染阶段
    constructor() ----- render() ----- componentDidMount()
  2. 数据更新,再次渲染阶段
    shouldComponentUpdate() ----- render() ------ componentDidUpdate()
  3. 销毁阶段
    componentWillUnmount
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值