gpt4 book ai didi

reactjs - React Hooks 会取代类吗?

转载 作者:行者123 更新时间:2023-12-03 13:21:26 24 4
gpt4 key购买 nike

现在 React 终于有了 hooks,这最终会成为创建组件的新标准还是仍然需要创建类组件?

据我了解,目前钩子(Hook) can not accomplish everything a class can 。例如,为 getSnapshotBeforeUpdate 和 componentDidCatch 的生命周期方法提供钩子(Hook)。然而,React 团队表示他们计划很快添加此功能。他们还提到有 no plans to remove classes来自 react 。

那么当所有生命周期方法都被支持时,还有什么理由创建类组件呢?此时类是否仍然比功能组件更好地处理某些情况?

最佳答案

我将礼貌地不同意上述评论。 Hooks 100% 是 React 的 future 。我强烈建议阅读Medium article Dan Abramov 在 2018 年 10 月写的文章。文章顶部还有一段 Dan Abramov 在上次 React Conf 上发表主题演讲的视频。在他的演讲中,他首次介绍了钩子(Hook)。他在地址末尾补充道,他不建议立即重构旧组件,但他确实建议使用 hooks 继续前进(这是当 hooks 仍是 alpha 版本时):

I ask you not to rewrite your whole apps in hooks...because personally I find that it takes a bit of a mind shift to start thinking in hooks, and it might be a bit confusing if you just try to take a class Component and convert it, but I do encourage you to try using hooks in some of the newer code that you're writing and let us know what you think.

他接着说:

So, in our view hooks represent our vision of the future of React. But, they also represent the way we move React forward, and that is that we don't do big re-writes. And, that is that we want the new patterns that we like better to co-exist with the old patterns.

如果你观看整个事情,他会更详细地讨论这个问题。我相信 Facebook 和 Dan Abramov 将 hooks 视为 React 的 future (我也是如此,但我的观点并不重要)。他们认为从钩子(Hook)中出现的模式明显优于由类组件建立的模式。他们还表示,他们打算维护类 Components 的原因是因为他们不打算重写 React 或引入重大更改。

由于使用有状态函数而不是扩展类,代码膨胀也更少。 Hooks 直接 Hook 到由 React 框架维护的全局应用程序状态,而不是通过抽象在本地维护它(这就是它们被称为 Hook 的原因)。 Hooks 通过 custom hooks 促进代码的可重用性。钩子(Hook)允许我们通过 useEffect 监控个体状态,而无需生命周期方法和条件。 。与类组件相比,使用钩子(Hook)还有很多其他好处,但我不想在这里写一本书。

除了列出的好处以及 Facebook 团队的赞扬之外,我还想指出所有添加对钩子(Hook)的支持的第三方库。 FAQ page您分享的内容表明 Redux 和 React Router 都计划发布对 hooks 的支持。事实上,Redux 维护者们已经兴奋不已 discussing hooks自从它们被介绍给公众以来。并且,Ryan Florence(React Router 的创建者)在 React Conf 上继 Dan Abrimov 之后发表了讲话。他实际上对 hooks 给予了更大的认可:

Dan just said "don't re-write your apps in hooks". I think you should.

除此之外,Material-UI version 4-alpha已经出来了,他们也引入了钩子(Hook)。

总而言之,hooks 是 React 的 future ,我们应该使用它们。自 React v16.8.0 起,它们就处于稳定版本中,并且没有理由不主要使用它们。

关于reactjs - React Hooks 会取代类吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54912470/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com