reactjs - react : Difference between a Stateful Class Component and a Function Component using Hooks?

标签 reactjs react-hooks react-component react-context

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

除了我已经发现的差异之外,这个有状态函数组件和有状态类组件之间还有什么区别吗?我的上述说法是否错误?

稍微细化一下这个问题,有什么事情是类组件可以做而带 Hooks 的函数组件做不到的吗?

最佳答案

上钩之前:

  • 有状态和无状态之间有明显的区别 组件。
  • 当您希望组件具有一些功能时,可以使用编写 状态,并且当您认为您的 组件不需要任何状态。

后钩:

  • 通过引入 Hooks,我们可以在不使用类的情况下创建有状态组件。

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

有用的文章

正如 Sung M. Kim 所说,react hooks 中有 3 个生命周期 hooks 尚未实现。

  1. 从Props获取DerivedState

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.

您可以使用 useEffectuseState Hook 实现相同的目的。 useEffect 接受因变量数组作为第二个参数,这将导致 useEffect 重新运行,因此您可以执行以下操作:

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

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

  • getDerivedStateFromError

  • 此钩子(Hook)捕获子树中的错误,但以下错误 ( 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)

    关于reactjs - react : Difference between a Stateful Class Component and a Function Component using Hooks?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57642594/

    相关文章:

    reactjs - antd表格中可以显示html格式的文本吗?

    javascript - 对象作为具有样式化组件的 React 子项无效

    reactjs - 如何在 Cypress 中测试 React Material UI Drawer 组件属性值

    javascript - React 在从 API 调用接收数据后不更新 UI(使用 Hook )

    javascript - 如果部分状态发生变化,如何停止 react 重新渲染组件?

    javascript - 在 reactjs 商店中找到不可调用的 @@iterator

    javascript - useRef 钩子(Hook)中的 "current"键是什么?

    reactjs - UseEffect 钩子(Hook)的 Jest 测试用例

    javascript - react : can't access passed props (but CAN access props from router)

    javascript - 如何处理从父组件到子组件的 Prop 以填充表单中的 Prop 数据以进行更新