何时以及如何在 React Hooks 和旧的 HOC props 之间进行选择? [英] When and how to choose between React Hooks and old HOC props passing?

查看:44
本文介绍了何时以及如何在 React Hooks 和旧的 HOC props 之间进行选择?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

直到现在我们都习惯了 Flux 流,数据通过 props 输入到组件中.因此,您可以查看 Props 签名并了解组件要求是什么.

Until now we were used to Flux flow where data entered into the component through props. So you could look at the Props signature and see what is the component requirements.

钩子是一个了不起的特性,但是当我们过渡到它们时,我发现它们为依赖项提供了另一个入口,这更难管理,因为你必须查看实际的组件代码才能看到它.

Hooks are an amazing feature, but as we transition to them I find that they provide another entrance for dependencies which is harder to manage since you have to look at the actual component code to see it.

当然,我们只能在容器组件中使用 Hooks,但是我觉得它们的一些主要卖点是它们能够减少嵌套和 HOC.

Of course, we can use Hooks only in container components, but I feel that some of their main selling points are their ability to reduce nesting and HOC.

决定哪个组件应该使用钩子以及哪个应该使用渲染道具的最佳实践(当前)是什么?

What are the best practices (currently) for deciding which component should use a hook and which should use render props?

推荐答案

Hooks 和 HOCs 是不同的编程模型,比较它们就像比较橙子和苹果一样.

Hooks and HOCs are different programmings models, and comparing them will seem to be as comparing oranges and apples.

TL;DR

根据经验,当我想要组件的条件渲染(如果条件:渲染 A,否则渲染 B)时,我使用 HOC,否则,我使用钩子.这只是我的看法.

As a rule of thumb, I use HOCs when I want a conditional rendering of components (if condition: render A, else render B), otherwise, I use hooks. That's only my opinion.

HOC 的优点

  • 轻松地将所有逻辑与 UI 组件分离(请参阅recompose).
  • 易于作曲.
  • 在任何渲染之前操作组件.
  • Easily separate all logic from the UI component (see recompose).
  • Easy to compose.
  • Manipulate component before any render.

HOC 的缺点

  • 名称冲突 - 2 个 HOC 可以使用和设置同名道具.
  • React dom 非常庞大.
  • 父 props 的每一次更改都会导致子级重新渲染 - 这是 React 中的默认行为,但是当我们有很多 HOC 时,我们需要非常小心.
  • 类型 - 从组件的角度来看,很难理解我们得到了哪些 props 和类型.
  • 使用 HOC 会将所有道具传递给孩子,即使孩子从该特定 HOC 中只需要道具 x.
  • 使用依赖于组件的 HOC 道具的参数的过程可能很复杂

HOCs Pro &两者兼而有之

  • 无需定义变量,只需用 HOC 包裹即可获得 HOC 提供的道具 - 这使得我们的 UI 组件猜测"道具的名称.

Hook 优点

  • 可读&声明式.
  • 性能 - 仅在更改特定道具时更新.
  • 不断壮大的社区.

Hook 缺点

  • 仅在组件内 - 这意味着不能通过传递的 props 条件渲染组件.
  • 包含 UI & 的巨型组件文件完全符合逻辑.

这篇关于何时以及如何在 React Hooks 和旧的 HOC props 之间进行选择?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆