react销毁方法钩子0_React钩子:使用React状态的新方法

React Hooks在React 16.8稳定版中引入,允许在函数组件中轻松管理状态,无需转换为类组件。 Hooks消除了对生命周期方法如`componentDidMount`的需求,引入了如`useEffect`等内置钩子。它们提高了代码复用性和组件可维护性,简化了逻辑和语法。文章通过示例解释了如何使用Hooks,并讨论了它们为何是React开发的良好选择。
摘要由CSDN通过智能技术生成

react销毁方法钩子0

Updated: With React 16.8, React Hooks are available in a stable release!

更新:随着React 16.8的发布, React Hooks已经发布!

Outdated: Hooks are still an experimental proposal. They’re currently in React v16.7.0-alpha

过时的:挂钩仍然是一个实验性的建议。 他们目前在React v16.7.0-alpha中

TL;DR In this article we will attempt to understand what are React Hooks and how to use them for our good. We will implement different examples and see the differences (gains) Hooks bring to us. If you want to skip the reading, here you can find shorter version in a few slides. And here ? you may get the examples and try them yourself.

TL; DR在本文中,我们将尝试了解什么是React Hooks以及如何将它们用于我们的利益。 我们将实现不同的示例,并查看Hooks带给我们的差异(收益)。 如果你想跳过读取, 在这里你可以找到几张幻灯片较短的版本。 在这里 ? 您可以获取示例并自己尝试。

什么是React Hooks(What are React Hooks?)

Simple functions for hooking into the React state and lifecycle features from function components.
用于从功能组件连接到React状态和生命周期功能的简单函数。

What this means is that hooks allow us to easily manipulate our function component’s state without needing to convert them into class components. This saves us from having to deal with all the boilerplate code involved.

这意味着钩子使我们能够轻松操纵函数组件的状态,而无需将其转换为类组件。 这使我们不必处理所有涉及的样板代码。

Hooks don’t work inside classes — they let you use React without classes. And also, by using them, we can totally avoid using lifecycle methods, such as componentDidMount, componentDidUpdate, etc. Instead, we will use built-in hooks like useEffect, useMutationEffect or useLayoutEffect. We will see how in a moment.

挂钩在类内部不起作用-它们使您可以在没有类的情况下使用React。 而且,通过使用它们,我们可以完全避免使用生命周期方法,例如componentDidMountcomponentDidUpdate等。相反,我们将使用诸如useEffectuseMutationEffectuseLayoutEffect之类的内置挂钩。 一会儿我们将看到。

Hooks are JavaScript functions, but they impose two additional rules:

挂钩是JavaScript函数,但是它们施加了两个附加规则

❗️ Only call Hooks at the top level. Don’t call Hooks inside loops, conditions, or nested functions.

Only️仅在顶层调用Hooks。 不要在循环,条件或嵌套函数中调用Hook。

❗️ Only call Hooks from React function components. Don’t call Hooks from regular JavaScript functions. There is just one other valid place to call Hooks — your own custom Hooks. We’ll see them later in this article.

Only️ 仅从React函数组件调用Hooks。 不要从常规JavaScript函数调用Hook。 还有另外一个有效的地方可以称为挂钩-您自己的自定义挂钩。 我们将在本文后面看到它们。

他们为什么是好东西? (Why are they good thing?)

? Reusing logicUp until now, if we wanted to reuse some logic in React, we had two options: higher-order components or render props. With React Hooks we have an alternative, that comes with a much easier to understand (in my personal opinion!) syntax and logic flow.

重用逻辑到现在为止,如果我们想重用React中的某些逻辑,我们有两个选择: 高阶组件渲染 道具。 有了React Hooks,我们有了另一种选择,它具有更容易理解的语法和逻辑流程(以我个人的观点!)。

? Giant componentsBy avoiding the boilerplate code we need to write when using classes or by removing the need for multiple nesting levels (which could come when using render props), React Hooks solve the issue of having giants components (that are really hard to maintain and debug).

大型组件通过避免使用类时需要编写的样板代码或消除对多个嵌套级别的需求(使用渲染道具时可能会出现),React Hooks解决了具有巨型组件的问题(实际上很难维护)并进行调试)。

? Confusing classesAgain, allowing us NOT to use classes or class components in our applications makes the developers’s (especially beginner’s) life easier. This is because we don’t have to use the ‘this’ keyword and we don’t need to have the understanding of how bindings and scopes work in React (and JavaScript).

çonfusing类再次,让我们不使用类或类组件在我们的应用使得开发商的(尤其是初学者),生活更轻松。 这是因为我们不必使用'this'关键字,也不需要了解在React(和JavaScript)中绑定和作用域是如何工作的。

This is NOT to say that we (the developers) don’t have to learn these concepts — on the contrary we must be aware of them. But in this case, when using React hooks, our worries are one fewer ?.

这并不是说我们(开发人员)不必学习这些概念,相反,我们必须意识到它们。 但是在这种情况下,当使用React钩子时,我们的担心少了一个?

So, after pointing out what issues the hooks solve, when would we use them?

那么,在指出了钩子解决了什么问题之后,我们什么时候才能使用它们呢?

If you write a function component and realize you need to add some state to it, previously you had to convert it to a class. Now you can use a Hook inside the existing function component. We’re going to do that in the next examples.

如果编写函数组件并意识到需要向其添加一些状态,则以前必须将其转换为类。 现在,您可以在现有功能组件中使用挂钩。 在下面的示例中,我们将进行此操作。

如何使用React Hooks(How to use React Hooks?)

React Hooks come to us as built-in ones and custom ones. The later are the ones we can use for sharing logic across multiple React components.

React Hooks是内置的自定义的 。 后者是我们可用于在多个React组件之间共享逻辑的组件。

As we’ve already learned, hooks are simple JavaScript functions, which means we will be writing just that, but in the context of React function components. Previously these components were called stateless, a term that is not valid anymore, as hooks give us a way to use the state in such components ?.

正如我们已经了解到的那样,钩子是简单JavaScript函数,这意味着我们将仅在React 函数组件的上下文中编写该函数 。 以前,这些组件称为无状态 ,该术语不再有效,因为钩子提供了一种在此类组件中使用状态的方法。

An important thing to remember is that we can use both built-in and custom hooks multiple times in our components. We just have to follow the rules of hooks.

要记住的重要一点是,我们可以在组件中多次使用内置和自定义钩子。 我们只需要遵循钩子规则即可

The following examples try to illustrate that.

以下示例试图说明这一点。

基本的内置挂钩 (Basic built-in hooks)
  • useState hook — returns a stateful value and a function to update it.

    useState hook —返回一个有状态的值和一个更新它的函数。

  • useEffect hook — accepts a function that contains imperative, possibly effectful code (for example fetching data or subscribing to a service). This hook could return a function that is being executed every time before the effect runs and when the component is unmounted — to clean up from the last run.

    useEffect挂钩—接受一个包含命令性的,可能有效的代码的函数(例如,获取数据或预订服务)。 每次运行效果之前和卸载组件时,此挂钩都可以返回正在执行的函数,以从上一次运行中清除。

  • useContext hook — accepts a context object and returns the current context value, as given by the nearest context provider for the given context.

    useContext hook —接受上下文对象,并返回当前上下文值,该值由最近的上下文提供者为给定上下文提供。

定制挂钩 (Custom hooks)

A custom Hook is a JavaScript function whose name starts with “use” and that may call other Hooks. For example, useFriendName below is our first custom Hook:

自定义挂钩是一个JavaScript函数,其名称以“ use ”开头,并且可以调用其他挂钩。 例如,下面的useFriendName是我们的第一个自定义Hook:

export default function useFriendName(friendName) {
  const [isPresent, setIsPresent] = useState(false);
  
  useEffect(() => {
    const data = MockedApi.fetchData();
    data.then((res) => {
      res.forEach((e) => {
        if (e.name === friendName) {
          setIsPresent(true);
        }
     });
    });
  });
    
  return isPresent;
}

Building your own custom hooks lets you extract component logic into reusable functions. This could be your application’s shared functionality that you can import everywhere you need it. And also, we must not forget, that our custom hooks are the other allowed (see the rules) places to call built-in hooks.

构建自己的自定义挂钩可以使您将组件逻辑提取到可重用的函数中。 这可能是您应用程序的共享功能,您可以将其导入所需的任何位置。 而且,我们也不要忘记,自定义钩子是调用内置钩子的另一个允许的位置( 请参阅规则 )。

结论 (Conclusion)

React Hooks are not really a new feature that popped out just now. They are another (better ❓) way of doing React components that need to have state and/or lifecycle methods. Actually, they use the same internal logic that is being used currently by the class components. To use them or not — this is the question to which the future will give the best answer.

React Hooks并不是刚刚出现的新功能。 它们是需要状态和/或生命周期方法的另一种(更好的)React组件。 实际上,它们使用与类组件当前正在使用的相同的内部逻辑。 是否使用它们-这是未来将给出最佳答案的问题。

My personal opinion? That this is going to be the future of any React development that involves state and lifecycle usage.

我个人的意见? 这将是任何涉及状态和生命周期使用的React开发的未来。

Let’s see how the community will react to the proposal ? and hopefully we will see them polished and fully functioning in the next React releases. ?

让我们看看社区将对该提案有何React? 希望我们在下一个React版本中能看到它们的完善和功能。 ?

? Thanks for reading! ?

? 谢谢阅读! ?

参考文献 (References)

Here you may find the links to the resources I found useful when writing this article:

在这里,您可能会找到指向我在撰写本文时有用的资源的链接:

翻译自: https://www.freecodecamp.org/news/hooking-with-react-hooks-964df4b23960/

react销毁方法钩子0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值