React:有状态 Class 组件和使用 Hooks 的函数组件之间的区别?

React: Difference between a Stateful Class Component and a Function Component using Hooks?

我刚刚创建了一个包含表达式 const [state, setState] = useState() 的函数组件。现在我可以访问 statesetState(),这个有状态函数组件与有状态 class 组件非常相似。我只知道此组件与典型的 class 组件之间的两个区别:在引用状态时,我们必须使用 state.handle 而不是 this.state.handle,并且我们可以轻松访问上下文API 在 render 方法之外。

除了我已经发现的差异之外,这个有状态功能组件和有状态 class 组件之间还有什么区别吗?我的上述说法不正确吗?

为了稍微细化一下这个问题,是否有什么是 Class 组件可以做而带有 Hooks 的函数组件不能做的?

函数和 class 之间有很多差异,它们体现在语法中。此外,组件 classes 中的生命周期方法不同于组件函数中的钩子。但最重要的是,您不会因为使用功能组件而错过任何功能。事实上,带钩子的函数组件现在是创建 React 组件的默认方式。这里还有更多:

https://reactjs.org/docs/hooks-intro.html

Hooks 之前:

  • 有状态和无状态之间有明显的区别 组件。
  • 当你想让你的组件有一些 状态,当你认为你的 组件不需要任何状态。

Hooks 之后:

  • Hooks的引入,我们可以不使用类.

  • 创建有状态组件
  • 我们可以使用函数来创建有状态的组件。

有用的文章

正如 Sung M. Kim 所说,有 3 个生命周期钩子尚未在 React 钩子中实现。

  1. getDerivedStateFromProps

As mentioned in the docs, getDerivedStateFromProps exists for only one purpose. It enables a component to update its internal state as the result of changes in props.

您可以使用 useEffect & useState 挂钩实现相同的效果。 useEffect 接受一个因变量数组作为第二个参数,这将导致 useEffect 重新运行,因此您可以执行以下操作:

  const [state1, changeState1] = useState(props.prop1);

useEffect(() => {
    changeState1(props.prop1)
}, [props.prop1]);
  1. componentDidCatch

  2. getDerivedStateFromError

此挂钩捕获子树中的错误,但以下 (docs) 除外:

Event handlers (learn more) Asynchronous code (e.g. setTimeout or requestAnimationFrame callbacks) Server side rendering Errors thrown in the error boundary itself (rather than its children)