【问题标题】:What is difference between lifecycle method and useEffect hook?生命周期方法和 useEffect 钩子有什么区别?
【发布时间】:2019-12-12 19:30:59
【问题描述】:

在组件类中,我们使用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`;
});

【问题讨论】:

标签: reactjs react-hooks


【解决方案1】:

当您使用基于类的组件时,您可以访问生命周期方法(如 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)

【讨论】:

    【解决方案2】:

    是的,它们是一样的

    最初只有class based components 支持生命周期方法。

    功能组件是纯粹的无状态组件。但是在 React 16.8 中,他们添加了 Hooks。 Hooks 可用于statelifecycle methods

    是的,你可以把useEffect Hook想象成componentDidMount、componentDidUpdate和componentWillUnmount的组合。

    【讨论】:

      猜你喜欢
      • 2021-01-09
      • 2021-08-21
      • 2021-02-04
      • 2015-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多