首页 > 解决方案 > 生命周期方法和 useEffect 钩子有什么区别?

问题描述

在类 Components 中,我们使用 componentDidMount、componentDidUpdate 生命周期方法来更新状态。前任)

componentDidMount() {
    document.title = `You clicked ${this.state.count} times`;
}

componentDidUpdate() {
    document.title = `You clicked ${this.state.count} times`;
}

它在每个渲染(componentDidUpdate)之后运行,包括第一次渲染(componentDidMount)。在 useEffect 钩子中,我们可以像这样实现这个功能

useEffect(() => {
    document.title = `You clicked ${count} times`;
});

这两种方法效果一样吗?

我阅读了 Reactjs.org 这一节,并在 React.js vs 16 上进行了尝试。我认为这两种方法具有相同的效果。

useEffect(() => {
    document.title = `You clicked ${count} times`;
});

标签: reactjsreact-hooks

解决方案


在使用基于类的组件时,您可以访问生命周期方法(如 componentDidMount、componentDidUpdat 等)。但是当你想使用一个功能组件并且你想使用生命周期方法时,你可以使用 useEffect 来实现这些生命周期方法。

对于您的问题,当您使用基于类的组件时,您已经预定义了所有生命周期方法并相应地触发了它们,但是使用 useEffect 您还需要根据您想要实现的生命周期方法使其起作用。请参见下面的示例。

//--------Using a class based component.

import React, { Component } from 'react'
export default class SampleComponent extends Component {
  componentDidMount() {
    // code to run on component mount
  }
render() {
    return (<div>foo</div>)
  }
}

//-----------Using a functional component

import React, { useEffect } from 'react'
const SampleComponent = () => {
  useEffect(() => {
    // code to run on component mount
  }, [])
return (<div>foo</div>)
}
export SampleComponent

它们几乎相同,但最大的区别在于实现,那里(基于类的组件)您有使用生命周期方法的自定义函数,但在这里(基于函数的组件)您使用 useEffect 实现您手动使用的每一个。但是开发人员选择功能组件而不是基于类,因为功能组件被认为比 CBC 更快。(45% Faster React Functional Components


推荐阅读