[英]Should class components still be used when functional components with hooks exist in React?
Hi I'm very new in React.嗨,我是 React 的新手。 I've started learning React in the past 2 weeks, and I'm currently making a website using the MERN stack with a friend.
我在过去 2 周内开始学习 React,目前我正在与朋友一起使用 MERN 堆栈制作网站。 I've been using class components whenever I saw a need for maintaining states, but I just discovered that hooks can mimic React classes and supposedly reduces code length, increases readability, and creates more maintainable code.
每当我看到需要维护状态时,我就一直在使用 class 组件,但我刚刚发现钩子可以模仿 React 类,并且据称可以减少代码长度,提高可读性,并创建更易于维护的代码。 So I'm just wondering, should class components be used in React as of 2020 when hooks exist?
所以我只是想知道,到 2020 年,当挂钩存在时,是否应该在 React 中使用 class 个组件? What use cases do classes cover that aren't covered by functional components?
类涵盖哪些功能组件未涵盖的用例?
Hooks are meant as a complete replacement for class components.挂钩旨在完全替代 class 组件。 From react docs ,
从反应文档,
We intend for Hooks to cover all existing use cases for classes , but we will keep supporting class components for the foreseeable future.
我们打算让 Hooks 涵盖类的所有现有用例,但在可预见的未来,我们将继续支持 class 个组件。
Reading the page linked above about the adoption strategy, the intent behind hooks - would be a great place to understand and form an opinion.阅读上面链接的关于采用策略的页面,钩子背后的意图 - 将是理解和形成意见的好地方。
Personally, I love hooks.就个人而言,我喜欢钩子。 And haven't used class components since hooks were introduced.
自从引入 hooks 以来,还没有使用过 class 个组件。 I am yet to find a use-case where I needed to use a class component because hooks couldn't satisfy the ask.
我还没有找到我需要使用 class 组件的用例,因为挂钩无法满足要求。
it's preference thing but the community is moving towards hooks.这是偏好的事情,但社区正在转向钩子。 Hooks + other features can pretty much cover everything done in hooks
Hooks + 其他功能几乎可以涵盖所有在 Hooks 中完成的事情
eg例如
useEffect
=> componentDidMount, componentDidUpdate, componentWillMount
useEffect
=> componentDidMount, componentDidUpdate, componentWillMount
useState
=> this.setState({})
useState
=> this.setState({})
React.memo
=> shouldComponentUpdate
React.memo
=> shouldComponentUpdate
some things are easier in classes than they are in hooks at the moment.目前,有些事情在课堂上比在钩子上更容易。 like the second argument in
setState
is a callback to ensure that state is changed before executing.就像
setState
中的第二个参数是一个回调,以确保在执行之前更改 state。 this is possible in hooks but it's not quite as clean as that这在钩子中是可能的,但它并不那么干净
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.