React Hooks 会取代 类 吗?

Will React Hooks Replace Classes?

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

我知道目前从 React 中钩子 can not accomplish everything a class can. Such as, providing hooks to lifecycle methods for getSnapshotBeforeUpdate and componentDidCatch. However, the React team has said they plan on adding this functionality soon. They also mention that there are no plans to remove classes

那么,当支持所有生命周期方法时,是否还有理由创建 class 组件?在这一点上,classes 是否仍然比功能组件更好地处理某些情况?

我要礼貌地不同意上面的评论。 Hooks 是 React 100% 的未来。我强烈推荐阅读 Dan Abramov 在 2018 年 10 月写的 Medium article。Dan Abramov 在上届 React Conf 上发表主题演讲的文章顶部还有一段视频。在他的演讲中,他首次介绍了钩子。他在地址末尾补充说,他不建议立即重构您的旧组件,但他确实建议继续使用 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 的未来(我也是,但我的观点并不重要)。他们认为从钩子中出现的模式明显优于 class Components 建立的模式。他们还表示他们打算维护 class 组件的原因是因为他们不打算重写 React 或引入重大更改。

由于使用有状态函数而不是扩展 classes,代码膨胀也更少。 Hooks 直接挂钩到由 React 框架维护的全局应用程序状态,而不是通过抽象在本地维护它(这就是它们被称为 hooks 的原因)。挂钩通过 custom hooks. Hooks allow us to monitor individual state without lifecycle methods and conditionals through useEffect 促进代码的可重用性。在 class 组件上使用钩子还有很多其他好处,但我不想在这里写一本书。

除了列出的好处和来自 Facebook 团队的赞扬之外,我还要指出所有正在添加对挂钩的支持的第三方库。 FAQ page you shared indicates that both Redux and React Router are planning on releasing support for hooks. In fact, the Redux maintainers have been excitedly discussing hooks 自从他们介绍到 public。并且,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 已经出来了,他们也引入了 hooks。

总而言之,hooks 是 React 的未来,我们应该使用它们。自 React v16.8.0 以来,它们处于稳定版本中,没有理由不在未来主要使用它们。