react hooks_为什么选择React Hooks,我们如何到达这里?

react hooks

by Ryan Yurkanin

瑞安·尤卡宁(Ryan Yurkanin)

为什么选择React Hooks,我们如何到达这里? (Why React Hooks, and how did we even get here?)

TL;DR: Hooks have learned from the trade-offs of mixins, higher order components, and render props to bring us new ways to create contained, composable behaviors that can be consumed in a flat and declarative manner. ?

TL; DR:鱼钩从混入的权衡,高阶组件了解到,和渲染道具给我们带来了新的方法来创建 包含的,可以在平坦和声明的方式来消耗组合的行为

However, hooks come with their own price. They are not the silver bullet solution. Sometimes you need hierarchy. So let’s take a closer look.

但是,挂钩有自己的价格。 它们不是解决方案的灵丹妙药。 有时您需要层次结构。 因此,让我们仔细看看。

React Hooks are here, and I immediately fell in love with them. To understand why Hooks are great, I think it helps to look at how we’ve been solving a common problem throughout React’s history.

React Hooks在这里,我立即爱上了它们。 为了理解Hooks为什么很棒,我认为这有助于我们了解React在整个历史中如何解决一个常见问题。

Here’s the situation. You have to show the user’s mouse position. ?

这是情况。 您必须显示用户的鼠标位置。 ?

However️但是有一些方法可以再次咬我们。 (⚠️ However there are some ways this can come back to bite us.)
  • If you need that mouse move behavior in another component you will have to rewrite the same code.

    如果您需要在其他组件中进行鼠标移动,则必须重写相同的代码。
  • If you add more behaviors like this, it will become harder to understand at first glance. This is because the behavior’s logic is spread across componentDidMount and componentWillUnmount ?

    如果您添加更多这样的行为,乍一看将变得更加难以理解。 这是因为行为的逻辑分布在componentDidMountcomponentWillUnmount

We’re engineers though, and we have a ton of tools to help us break this pattern out. Let’s review some of the ways we’ve historically done it and their trade-offs. ?

虽然我们是工程师,但我们有大量工具可以帮助我们突破这种模式。 让我们回顾一下我们过去做过的一些方法及其取舍。 ?

混合蛋白 (Mixins)

Mixins get a lot of flak. They set the stage for grouping together lifecycle hooks to describe one effect.

Mixins变得很多。 他们为将生命周期挂钩组合在一起以描述一种效果奠定了基础。

While the general idea of encapsulating logic is great, we ended up learning some serious lessons from mixins.

尽管封装逻辑的一般想法很棒,但我们最终还是从mixin学习了一些严肃的经验 。

It’s not obvious where this.state.x is coming from. With mixins, it’s also possible for the mixin to be blindly relying on that a property exists in the component.

这不是很明显this.state.x来自哪里。 使用mixin时,mixin也可能会盲目地依赖组件中存在的属性。

That becomes a huge problem as people start including and extending tons of mixins. You can’t simply search in a single file and assume you haven’t broken something somewhere else.

随着人们开始包括并扩展大量的mixin,这成为一个巨大的问题。 您不能简单地在单个文件中搜索并假设您没有破坏其他地方的内容。

Refactoring needs to be easy. These mixed-in behaviors need to be more obvious that they don’t belong to the component. They shouldn’t be using the internals of the component. ?‍

重构需要很容易。 这些混合行为必须更加明显,因为它们不属于该组件。 他们不应该使用组件的内部。 ‍

高阶组件 (Higher Order Components)

We can achieve a similar effect, and make it a bit less magical by creating a container that passes in props! Inheritance’s main trade-off is it makes refactoring harder, so let’s try composition!

我们可以实现类似的效果,并通过创建一个传递道具的容器使它的魔力降低一些! 继承的主要折衷是它使得重构更加困难,因此让我们尝试组合!

While this is more code, we are moving in the right direction. We have all the benefits of Mixins. Now we have a /> component that is no longer tightly coupled to the subscription behavior.

尽管这是更多的代码,但我们正在朝着正确的方向发展。 我们拥有Mixins的所有优势。 现在,我们有了一个 />组件,它不再与订阅行为紧密耦合。

What if we wanted to render something different though? Do we always need to make a new component?

如果我们想渲染一些不同的东西怎么办? 我们是否总是需要制作一个新组件?

渲染道具和儿童功能 (Render Props & Children as a Function)

This is the pattern that has been staring us in the face the entire time. All we want is a component that handles the mouse move behavior, and the ability to render whatever we want.

这是一直以来我们一直盯着我们看的模式。 我们所需要的只是一个处理鼠标移动行为的组件,以及呈现所需内容的能力。

这种微妙的区别有一些非常棒的好处 (This subtle difference has some pretty awesome benefits)
  • It is now super obvious what is providing x and y. You can also easily rename them to prevent name collisions.

    现在非常明显的是提供xy 。 您也可以轻松地重命名它们以防止名称冲突。

  • We have flexible control over what is rendering. We don’t need to be making new components, and if we decide to, it’s just a simple copy paste.

    我们可以灵活控制渲染内容。 我们不需要制作新的组件,而且如果我们决定这样做,那只是简单的复制粘贴。
  • You can see all of this directly in a components render function. It’s in plain sight and easy for new developers coming in to identify. cmd + f checks out here.

    您可以直接在组件渲染功能中查看所有这些信息。 这是显而易见的,新来的开发人员很容易识别。 cmd + f在这里签出。

The main problem with this pattern is that your components are bound to nest quite a few of these in their renders. Once you start nesting multiple render prop components, it can be incredibly hard to reason what is going on.

这种模式的主要问题是,您的组件必须在其渲染中嵌套很多组件。 一旦开始嵌套多个渲染道具组件,就很难推理发生了什么。

Also, it creates a false sense of hierarchy. Just because a behavior is “nested” under another behavior doesn’t mean it relies on the parent behavior. Take for example this snippet.

此外,它还会产生错误的层次感。 仅仅因为一个行为被“嵌套”在另一个行为下并不意味着它依赖于父行为。 以这个片段为例。

If only there was a way to have all this power, in a declarative AND flat way. ?

如果只有一种方法能够以声明性和统一的方式拥有所有这些权力。

钩子 (Hooks)

What if we could remove the nesting, and bubble everything up to the top? That way the only JSX in our render function is pure rendering logic.

如果我们可以移除嵌套并将所有气泡冒到顶部怎么办? 这样,我们的渲染函数中唯一的JSX是纯渲染逻辑。

This is everything I ever wanted.

这就是我想要的一切。

  • Not only is the behavior in its own neat little package, useEffect stops it from being spread across three different lifecycle hooks

    行为不仅在其自己的简洁小程序包中, useEffect阻止了它分散在三个不同的生命周期挂钩中

  • Where the component is getting this data from is incredibly clear, it’s nestled neatly inside the render function.

    组件从何处获取此数据非常清楚,它被整齐地嵌套在render函数中。
  • No matter how many of these I need to bring in, my code won’t become increasingly nested.

    无论我需要引入多少,我的代码都不会越来越嵌套。

Sunil Pai used some clever highlighting in the tweet below to illustrate how effective hooks are at not just reducing the total amount of code, but also grouping together related parts.

Sunil Pai在下面的推文中使用了一些巧妙的突出显示来说明钩子如何有效地不仅减少了代码的总量,而且将相关部分组合在一起。

但是,有一些问题 (However, there are some catches)

When using hooks, you have to remember a couple of rules that may seem weird at first:

使用钩子时,必须记住一些规则,乍一看似乎很奇怪:

You️您应该在render函数的顶层调用钩子。 (⚠️ You should call hooks at the top level of the render function.)

This means no conditional hooks. Our contract with React is that we will call the same amount of hooks, in the same order every time.

这意味着没有条件挂钩。 我们与React的合同是,我们将以相同的顺序调用相同数量的钩子。

This rule starts to make more sense when you compare it to how Mixins, and HOCs work. You can’t conditionally use them and reorder them on each render.

将其与Mixins和HOC的工作方式进行比较时,此规则开始变得更有意义。 您不能有条件地使用它们并在每个渲染上对其重新排序。

If you want conditional effects, you should split your hooks into other components, or consider a different pattern.

如果需要条件效果,则应将钩子拆分为其他组件,或考虑使用其他模式。

️️⚠️ 您只能在React Function Components和Custom Hooks中使用钩子。 (️️⚠️ You can only use hooks in React Function Components, and in Custom Hooks.)

I’m not sure if there’s actually any technical reason to not try calling them in a regular function. This ensures that the data is always visible in the component file.

我不确定实际上是否有任何技术原因不尝试在常规函数中调用它们。 这样可以确保数据在组件文件中始终可见。

⚠️ 没有为componentDidCatch或getSnapshotBeforeUpdate挂钩的原语。 (⚠️ There aren’t hook primitives for componentDidCatch or getSnapshotBeforeUpdate.)

The React team says they are on their way though!

React团队说他们正在路上!

For the componentDidCatch use case, you could create an Error Boundary component, getSnapshotBeforeUpdate is a bit trickier, but fortunately pretty rare.

对于componentDidCatch用例,您可以创建一个错误边界组件,getSnapshotBeforeUpdate有点棘手,但是幸运的是很少见。

最后注意事项 (Some Final Notes)

I have no doubt that hooks are about to change the way we view React, and shake up some best practices. The amount of excitement and libraries coming out is inspiring!

我毫不怀疑,挂钩将改变我们查看React的方式,并改变一些最佳实践。 大量的激动和图书馆鼓舞人心!

However, I have seen the hype for all of these design patterns in the past. While most have ended up being very valuable tools in our toolboxes, they all come with a price.

但是,过去我已经看到了所有这些设计模式的炒作。 尽管大多数最终成为我们工具箱中非常有价值的工具,但它们都带有价格。

I still don’t fully understand the trade-offs of hooks, and that scares me. I highly suggest playing around with them, and learning by example. You should probably wait a bit before doing a full rewrite in them though ?

我仍然不完全了解挂钩的权衡,这使我感到恐惧。 我强烈建议与他们一起玩耍,并以身作则。 您可能应该等待一会儿再对它们进行完全重写吗?

If you have any questions or are looking for one-on-one React mentorship, feel free to tweet me @yurkaninryan any time!

如果您有任何疑问或正在寻找一对一的React指导,请随时在@yurkaninryan上发消息给我!

If you like my writing style, here are some other articles that I’ve done.

如果您喜欢我的写作风格,这是我做过的其他文章。

Good luck and happy coding!! ?

祝你好运,编码愉快!! ?

翻译自: https://www.freecodecamp.org/news/why-react-hooks-and-how-did-we-even-get-here-aa5ed5dc96af/

react hooks

你可能感兴趣的:(java,python,设计模式,人工智能,vue,ViewUI)