简体   繁体   English

React - 曾经使用过类组件吗?

[英]React - Are class components ever used?

I'm going through some courses that were made before react hooks were a thing, now I'm wondering if there is any reason at all to use class-based components over functional components now that hooks exist?我正在学习一些在反应钩子成为事物之前制作的课程,现在我想知道既然钩子存在,是否有任何理由使用基于类的组件而不是功能组件?

I can't seem to come up with a reason or scenario where a class-based component would be preferable, but maybe I'm just not aware of certain corner-cases where a class-based component would be the go-to choice.我似乎无法提出基于类的组件更可取的原因或场景,但也许我只是不知道基于类的组件将成为首选的某些极端情况。

Appreciate any feedback regarding this.感谢您对此的任何反馈。

Thanks in advance!提前致谢!

Class components are still used, but there is no particular reason to continue to do so.仍然使用类组件,但没有特别的理由继续这样做。 Tthe Facebook team recommends that all new React code is hook-based functional components, and not class-based. Facebook 团队建议所有新的 React 代码都是基于钩子的功能组件,而不是基于类的。 You can mix class components and hook-based components, so there is no reason to rewrite your class components.您可以混合使用类组件和基于钩子的组件,因此没有理由重写您的类组件。

You can read more at https://reactjs.org/docs/hooks-faq.html您可以在https://reactjs.org/docs/hooks-faq.html阅读更多内容

At the company I work for we have mixture of both since we started using react before hooks.在我工作的公司,自从我们开始使用钩子之前的反应以来,我们两者都有。 In my experience class components tend to have a lot more state logic, are fatter, tightly coupled, and harder to test.根据我的经验,类组件往往有更多的状态逻辑,更胖,更紧密耦合,更难测试。 However, even though we're moving towards developing functional components, some people coming from ac# background tend to pick up class based components more easily.然而,即使我们正朝着开发功能组件的方向发展,一些来自 ac# 背景的人倾向于更容易地选择基于类的组件。 I would highly suggest using functional components but depending on the background of your team it might not hurt in the short run to use class based ones.我强烈建议使用功能组件,但根据您团队的背景,短期内使用基于类的组件可能不会受到伤害。

The only good reason that I can think of for using class components these days would be to create error boundaries as:这些天我能想到使用类组件的唯一充分理由是创建错误边界:

Only class components can be error boundaries.只有类组件可以是错误边界。

From https://reactjs.org/docs/error-boundaries.html来自https://reactjs.org/docs/error-boundaries.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM