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://github.com/mihailgaberov/react-hooks/ — link to GitHub repo with the examples and presentation.

    https://github.com/mihailgaberov/react-hooks/ —通过示例和演示文稿链接到GitHub存储库。

  • https://mihailgaberov.github.io/react-hooks/ — link to presentation slides.

    https://mihailgaberov.github.io/react-hooks/-链接到演示幻灯片。

  • https://reactjs.org/docs/hooks-intro.html — official ReactJS blog.

    https://reactjs.org/docs/hooks-intro.html-ReactJS官方博客。

  • https://youtu.be/dpw9EHDh2bM — Introduction to Hooks, React Conf 2018

    https://youtu.be/dpw9EHDh2bM-Hooks简介,React Conf 2018

  • https://medium.com/@dan_abramov/making-sense-of-react-hooks-fdbde8803889 — An explanatory article by Dan Abramov.

    https://medium.com/@dan_abramov/making-sense-of-react-hooks-fdbde8803889-Dan Abramov的说明性文章。

  • https://daveceddia.com/useeffect-hook-examples/ — A very useful article explaining different use cases of useEffect hook.

    https://daveceddia.com/useeffect-hook-examples/ —一篇非常有用的文章,介绍了useEffect钩子的不同用例。

  • https://ppxnl191zx.codesandbox.io/ — An example of a React animation library experimenting with Hooks.

    https://ppxnl191zx.codesandbox.io/ —一个使用Hooks进行实验的React动画库的示例。

  • https://dev.to/oieduardorabelo/react-hooks-how-to-create-and-update-contextprovider-1f68 — A nice and short article showing how to create and update context provider with React Hooks.

    https://dev.to/oieduardorabelo/react-hooks-how-to-create-and-update-contextprovider-1f68 —一篇不错的简短文章,展示了如何使用React Hooks创建和更新上下文提供程序。

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

react销毁方法钩子0

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

  1. 亚马逊训练alexa的方法_Alexa对话是AI驱动的对话界面新方法

    亚马逊训练alexa的方法 介绍 (Introduction) Looking at the chatbot development tools and environments currently ...

  2. ajax请求成功和失败方法_创新需要反馈和失败的新方法

    ajax请求成功和失败方法 今天,"组织文化"令人不解,有充分的理由. 越来越多的领导者意识到,渗透并指导其组织的文化将决定他们是成功还是失败. 术语"组织文化" ...

  3. 数学模型天气预测方法_预测即将到来的天气的新方法

    数学模型天气预测方法 By: Teja Balasubramanian 创建人:Teja Balasubramanian A new wave arises. Computer programming ...

  4. 一个方法多个return_CVPR 2020(Oral) | 旷视提出CrowdDetection:密集场景检测新方法:一个候选框,多个预测结果...

    点击上方"CVer",选择加"星标"或"置顶" 重磅干货,第一时间送达 本文转载自:旷视研究院 本文是CVPR 2020论文系列解读第8篇. ...

  5. 计算机提取干涉条纹原理,两种提取Fabry-Perot干涉条纹圆心的新方法

    摘要本文介绍两种提取Fabry-Perot干涉条纹圆心点坐标的新方法.首先对干涉图像依次进行二值化处理,对所得到的条纹强度曲线进行均平滤波和自适应滤波,根据条纹灰度值强度余弦函数分布的特点,对条纹灰度 ...

  6. 手机网站php模板修改,Phpcms V9自定义手机WAP模板新方法

    近来越来越多手机WAP.自适应网站,可见移动网页是未来,响应式是未来!但是在实际经验中,CMSYOU发现:响应式自适应虽然在国外非常流行了.大家都在追随,不过在国内,由于XP上ie6.IE8,带宽等问 ...

  7. react钩子_迷上了钩子:如何使用React的useReducer()

    react钩子 So the React Conference just happened and as always something new happened. Hooks happened! ...

  8. react全局方法_前端面试题 ---react

    高阶组件相关 什么是高阶组件,它有哪些运用? 高阶组件就是一个函数,接收一个组件,经过处理后返回后的新的组件: 高阶组件,不是真正意义上的组件,其实是一种模式: 可以对逻辑代码进行抽离,或者添加某个共 ...

  9. react绑定this_React绑定模式:处理“ this”的5种方法

    react绑定this JavaScript's this keyword behavior has confused developers for ages. JavaScript的this关键字行 ...

最新文章

  1. java linux 起多个进程_linux下tomcat启动后出现多个java进程
  2. Appium下载安装及环境配置
  3. 9月4日服务器例行维护公告,《诺亚传说手游》官网-【例行维护】9月4日官方维护公告(抢鲜服)- 诺亚手游-首款科幻团战手游...
  4. Docker创建虚机和swarm
  5. vs2008下设置.h, .lib和 .dll 的路径配置全图及其意义
  6. HTTP知识普及系列:HTTP首部
  7. 信息学奥赛一本通 1015:计算并联电阻的阻值 | OpenJudge NOI 1.3 10
  8. 信息系统综合知识二 信息化基础知识
  9. 树莓派运用阿里云API实现语音识别
  10. dev、test 和 prod 是什么意思?
  11. iOS IPA包路径,分析百度统计崩溃日志
  12. C++ BMP转JPG方法三
  13. background简写方式
  14. 摆脱五彩斑斓的黑,成为七彩程序员!
  15. OC循环渐进:文件管理--计算文件大小的五种方式
  16. laravel导出excel
  17. 机器学习(九)基于SVM的上证指数涨跌预测
  18. ios 开发中遇到的一些问题
  19. 如何使用Google Scholar(谷歌学术)
  20. 跟着老猫来搞GO,集跬步而致千里

热门文章

  1. C++11并发编程:多线程std::thread
  2. Silverlight 2 Beta 1版本缺陷列表
  3. ASP.NET 2.0 之 Master Page 学习笔记
  4. ADD_SHORTCUT_ACTION
  5. 为什么要在密码里加点“盐”
  6. NTP时间服务器实现Linux时间同步
  7. windows 停止nginx
  8. keytool 错误: java.io.IOException: Keystore was tampered with, or password was incorrect
  9. WebSnapshotsHelper(HTML转换为图片)
  10. 教程:在 VM Depot 中查找 Azure 可用的虚拟机镜像