react-hooks_在5分钟内学习React Hooks-初学者教程

react-hooks

Sometimes 5 minutes is all you've got. So in this article, we're just going to touch on two of the most used hooks in React: useState and useEffect.

有时只有5分钟。 因此,在本文中,我们仅涉及React中两个最常用的钩子: useStateuseEffect

If you're not famliar with hooks, here's the TL;DR: because of hooks, there's almost no more need for class-based components. Hooks let you "hook into" the underlying lifecycle and state changes of a component within a functional component. More than that, they often also improve readability and organization of your components.

如果您不熟悉钩子,请参阅TL; DR:由于有了钩子,几乎不再需要基于类的组件。 挂钩使您可以“挂钩”功能组件内组件的基础生命周期和状态更改。 不仅如此,它们还经常提高组件的可读性和组织性。

If you want a proper introduction to this subject, you can join the waitlist for my upcoming advanced React course, or if you're still a beginner, check out my introductory course on React.

如果您想对该主题进行适当的介绍,可以加入我即将举行的高级React课程的候补名单,或者如果您仍然是初学者,请查看我的React入门课程。

useState (useState)

Let's begin with a functional component.

让我们从功能组件开始。

import React from 'react';function App() {return (<div><h1>0</h1><button>Change!</button></div>);
}

Counter at 0

As you can see, nothing fancy at the moment. We're just rendering some text and a (useless) button.

如您所见,目前没有任何幻想。 我们只是渲染一些文本和一个(无用的)按钮。

Now let's import our very first hook, useState to learn how to handle state in our functional component.

现在,让我们导入我们的第一个钩子useState以学习如何处理功能组件中的状态。

As this hook is a function, let's console.log what we get returned from it.

由于此钩子是一个函数,因此,请console.log从钩子返回的内容。

import React, { useState } from 'react';function App() {const value = useState();console.log(value);return (<div><h1>0</h1><button>Change!</button></div>);
}

In the console, we get an array

在控制台中,我们得到一个数组

> [null, ƒ()]

And when we pass an argument to useState

当我们将参数传递给useState

const value = useState(true);

In the console, we get an array with our value as the first member.

在控制台中,我们得到一个以我们的值作为第一个成员的数组。

> [true, ƒ()]

Now, in our component, we can access our state at value[0] and render it in <h1> instead of a hardcoded value.

现在,在组件中,我们可以访问value[0]处的状态,并在<h1>呈现它,而不是硬编码值。

import React, { useState } from 'react';function App() {const value = useState(0);console.log(value); // [0, ƒ()]return (<div><h1>{value[0]}</h1><button>Change!</button></div>);
}

Counter at 0

We can improve our code by using array destructuring to store the value from useState hook. It's similar to object destructuring, which tends to be a bit more commonly seen. In case you're not super familiar with object destructuring, here's a quick recap:

我们可以通过使用数组解构来存储useState挂钩中的值来改进代码。 这类似于对象解构,后者往往更常见。 如果您对对象分解不太熟悉,请快速回顾一下:

const person = {name: 'Joe',age: 42
};// creates 2 const values from person object
const { name, age } = person;
console.log(name); // 'Joe'
console.log(age); // 42

Array destructing is almost the same, but uses square brackets [] instead of curly braces {}.

数组销毁几乎相同,但是使用方括号[]代替大括号{}

A quick tip: in object destructuring, the names of created variables must match the names of properties in the object. For array destructuring, that's not the case. It's all about the order. The benefit here is we can name the items whatever we want.

快速提示:在对象分解中,创建的变量的名称必须与对象中的属性的名称匹配。 对于数组解构,情况并非如此。 都是为了订单。 这样做的好处是我们可以随意命名项目。

Using array destructuring, we can get the initial value of state from the useState() hook.

使用数组解构,我们可以从useState()挂钩中获取state的初始值。

import React, { useState } from 'react';function App() {// remember, there's a second item from the array that's missing here, but we'll come right back to use it soonconst [count] = useState(0);  return (<div><h1>{count}</h1><button>Change!</button></div>);
}

OK, we've got the initial state value. How do we change the value in the state with hooks?

好的,我们已经有了初始状态值。 我们如何使用钩子更改状态值?

Remember that useState() hook returns an array with 2 members. The second member is a function that updates the state!

请记住, useState()挂钩返回一个包含2个成员的数组。 第二个成员是一个更新状态的函数!

const [count, setCount] = useState(0);

You can, of course, call it what you wish, but by convention, it's normally called with prefix "set-", and then whatever state variable we wish to update was called, so setCount it is.

您当然可以将其命名为所需的名称,但是按照惯例,通常使用前缀“ set-”来调用它,然后调用我们希望更新的任何状态变量,因此使用setCount

It's simple to use this function. Just call it and pass the new value you want that state to have! Or, just like this.setState in a class component, you can pass a function that receives the old state and returns the new state. Rule of thumb: do this anytime you need to rely on the past state to determine the new state.

使用此功能很简单。 只需调用它并传递您希望该状态具有的新值即可! 或者,就像类组件中的this.setState一样,您可以传递一个接收旧状态并返回新状态的函数。 经验法则:只要您需要依靠过去的状态来确定新的状态,就可以执行此操作。

To call it, we'll pass it to the onClick event listener. And just like with a regular setState in a class-based component, we can pass our state update to setCount.

要调用它,我们将其传递给onClick事件侦听器。 就像在基于类的组件中使用常规setState一样,我们可以将状态更新传递给setCount

function App() {const [count, setCount] = useState(0);return (<div><h1>{count}</h1><button onClick={() => setCount(prevCount => prevCount + 1)}>Change!</button></div>);
}

We can clean this up a bit, by extracting our state update to a separate function.

通过将状态更新提取到单独的函数中,我们可以进行一些清理。

function App() {const [count, setCount] = useState(0);function change() {setCount(prevCount => prevCount + 1);}return (<div><h1>{count}</h1><button onClick={change}>Change!</button></div>);
}

Great! And now when we can see the counter going up when we click the button.

大! 现在,当我们单击按钮时可以看到计数器在上升。

Counter at 1

Of course, useState can get a lot more complicated than this, but we've only got 5 minutes here, so let's move on to the next hook for now.

当然, useState可能比这复杂得多,但是这里只有5分钟,所以现在让我们继续下一个钩子。

useEffect (useEffect)

Hooks have simplified quite a few things, compared to the way things were in class-based components. Previously we needed to know a bit about lifecycle methods and which one is best suited for which situation. useEffect hook simplified this situation. If you wish to perform side effects, network request, manual DOM manipulation, event listeners or timeouts and intervals.

与基于类的组件相比,钩子简化了很多事情。 以前,我们需要对生命周期方法有所了解,并且哪种方法最适合哪种情况。 useEffect钩子简化了这种情况。 如果您希望执行副作用,网络请求,手动DOM操作,事件侦听器或超时和间隔。

useEffect hook can be imported just like useState.

useEffect钩子可以像useState一样useState

import React, { useState, useEffect } from 'react';

To make useEffect do something, we pass it an anonymous function as an argument. Whenever React re-renders this component, it will run the function we pass to useEffect.

为了使useEffect有所作为,我们将其传递给匿名函数作为参数。 每当React重新渲染此组件时,它将运行我们传递给useEffect的函数。

useEffect(() => {/* any update can happen here */
});

This is what the whole code might look like.

这就是整个代码的样子。

import React, { useState, useEffect } from 'react';function App() {const [count, setCount] = useState(0);function change() {setCount(prevCount => prevCount + 1);}useEffect(() => {/* any update can happen here */});return (<div><h1>{count}</h1><button onClick={change}>Change!</button></div>);
}export default App;

As an example, we will use a nice npm package that generates a random color. Feel free to write your own if you wish of course, but for this tutorial, we will just install it, npm i randomcolor, and import.

例如,我们将使用一个不错的npm包,该包会生成随机颜色。 当然,如果愿意,可以自己编写,但是对于本教程,我们将直接安装它, npm i randomcolor并导入。

import randomcolor from 'randomcolor';

Let's now use our knowledge about useState hook to store some random color in the state.

现在,让我们使用关于useState挂钩的知识在状态中存储一些随机颜色。

const [color, setColor] = useState(''); // initial value can be an empty string

We then can then assign the color of the counter we already have.

然后,我们可以分配已有的计数器的颜色。

<h1 style={{ color: color }}>{count}</h1>

Now, just for the sake of it, let's change the color of the counter on every click of the Change! button. useEffect will run every time the component re-renders, and the component will re-render every time the state is changed.

现在,仅出于此目的,让我们在每次单击Change!计数器的颜色Change! 按钮。 useEffect将在每次重新渲染组件时运行,并且每次在状态更改时都将重新渲染组件。

So if we write the following code, it would get us stuck in an infinite loop! This is a very common gotcha with useEffect

因此,如果我们编写以下代码,它将使我们陷入无限循环! 这是useEffect的非常常见的useEffect

useEffect(() => {setColor(randomcolor());
});

setColor updates state, which re-renders the component, which calls useEffect, which runs setColor to update the state, which re-renders the component... Yikes!

setColor更新状态,此状态将重新渲染该组件,并调用useEffect ,后者将运行setColor来更新状态,该状态将重新渲染该组件……kes!

We probably only want to run this useEffect when the count variable changes.

我们可能需要运行这个useEffectcount变量的变化。

To tell useEffect which variable(s) to keep track of, we give an array of such variables as a second argument.

为了告诉useEffect哪个变量,我们将此类变量的数组作为第二个参数。

useEffect(() => {setColor(randomcolor());
}, [count]);

Counter at 2

This basically says "only run this effect if the count state changes. This way we can change the color and not cause our effect to run infinitely.

这基本上说“只运行,如果这种影响count状态的变化。这样我们就可以改变颜色,并没有引起我们的影响无限运行。

结论 (Conclusion)

There's a lot more to learn about hooks, but I hope you've enjoyed this quick 5-minute peek into hooks.

关于钩子,还有很多要学习的东西,但我希望您喜欢这种快速的5分钟速览钩子。

To learn more about React Hooks and other great features of React, you can join the waitlist for my upcoming advanced React course. Or if you're looking for a more beginner friendly you can check out my introductory course on React.

要了解有关React Hooks和React其他重要功能的更多信息,可以加入我即将举行的高级React课程的候补名单。 或者,如果您正在寻找对初学者更友好的内容,则可以查看我关于React的入门课程。

Happy coding 🤠

快乐编码🤠

翻译自: https://www.freecodecamp.org/news/react-hooks-in-5-minutes/

react-hooks

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/390847.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

分析工作试用期收获_免费使用零编码技能探索数据分析

分析工作试用期收获Have you been hearing the new industry buzzword — Data Analytics(it was AI-ML earlier) a lot lately? Does it sound complicated and yet simple enough? Understand the logic behind models but dont know how to code? Apprehensive of spendi…

select的一些问题。

这个要怎么统计类别数呢&#xff1f; 哇哇哇 解决了。 之前怎么没想到呢&#xff1f;感谢一楼。转载于:https://www.cnblogs.com/AbsolutelyPerfect/p/7818701.html

重学TCP协议(12)SO_REUSEADDR、SO_REUSEPORT、SO_LINGER

1. SO_REUSEADDR 假如服务端出现故障&#xff0c;主动断开连接以后&#xff0c;需要等 2 个 MSL 以后才最终释放这个连接&#xff0c;而服务重启以后要绑定同一个端口&#xff0c;默认情况下&#xff0c;操作系统的实现都会阻止新的监听套接字绑定到这个端口上。启用 SO_REUSE…

残疾科学家_数据科学与残疾:通过创新加强护理

残疾科学家Could the time it takes for you to water your houseplants say something about your health? Or might the amount you’re moving around your neighborhood reflect your mental health status?您给植物浇水所需的时间能否说明您的健康状况&#xff1f; 还是…

Linux 网络相关命令

1. telnet 1.1 检查端口是否打开 执行 telnet www.baidu.com 80&#xff0c;粘贴下面的文本&#xff08;注意总共有四行&#xff0c;最后两行为两个空行&#xff09; telnet [domainname or ip] [port]例如&#xff1a; telnet www.baidu.com 80 如果这个网络连接可达&…

spss23出现数据消失_改善23亿人口健康数据的可视化

spss23出现数据消失District Health Information Software, or DHIS2, is one of the most important sources of health data in low- and middle-income countries (LMICs). Used by 72 different LMIC governments, DHIS2 is a web-based open-source platform that is used…

01-hibernate注解:类级别注解,@Entity,@Table,@Embeddable

Entity Entity:映射实体类 Entity(name"tableName") name:可选&#xff0c;对应数据库中一个表&#xff0c;若表名与实体类名相同&#xff0c;则可以省略。 注意&#xff1a;使用Entity时候必须指定实体类的主键属性。 第一步&#xff1a;建立实体类&#xff1a; 分别…

COVID-19研究助理

These days scientists, researchers, doctors, and medical professionals face challenges to develop answers to their high priority scientific questions.如今&#xff0c;科学家&#xff0c;研究人员&#xff0c;医生和医学专家面临着挑战&#xff0c;无法为其高度优先…

Go语言实战 : API服务器 (8) 中间件

为什么需要中间件 我们可能需要对每个请求/返回做一些特定的操作&#xff0c;比如 记录请求的 log 信息在返回中插入一个 Header部分接口进行鉴权 这些都需要一个统一的入口。这个功能可以通过引入 middleware 中间件来解决。Go 的 net/http 设计的一大特点是特别容易构建中间…

缺失值和异常值的识别与处理_识别异常值-第一部分

缺失值和异常值的识别与处理&#x1f4c8;Python金融系列 (&#x1f4c8;Python for finance series) Warning: There is no magical formula or Holy Grail here, though a new world might open the door for you.警告 &#xff1a; 这里没有神奇的配方或圣杯&#xff0c;尽管…

leetcode 664. 奇怪的打印机(dp)

题目 有台奇怪的打印机有以下两个特殊要求&#xff1a; 打印机每次只能打印由 同一个字符 组成的序列。 每次可以在任意起始和结束位置打印新字符&#xff0c;并且会覆盖掉原来已有的字符。 给你一个字符串 s &#xff0c;你的任务是计算这个打印机打印它需要的最少打印次数。…

PHP7.2 redis

为什么80%的码农都做不了架构师&#xff1f;>>> PHP7.2 的redis安装方法&#xff1a; 顺便说一下PHP7.2的安装&#xff1a; wget http://cn2.php.net/distributions/php-7.2.4.tar.gz tar -zxvf php-7.2.4.tar.gz cd php-7.2.4./configure --prefix/usr/local/php…

梯度 cv2.sobel_TensorFlow 2.0中连续策略梯度的最小工作示例

梯度 cv2.sobelAt the root of all the sophisticated actor-critic algorithms that are designed and applied these days is the vanilla policy gradient algorithm, which essentially is an actor-only algorithm. Nowadays, the actor that learns the decision-making …

垃圾回收算法优缺点对比

image.pngGC之前 说明&#xff1a;该文中的GC算法讲解不仅仅局限于某种具体开发语言。 mutator mutator 是 Edsger Dijkstra 、 琢磨出来的词&#xff0c;有“改变某物”的意思。说到要改变什么&#xff0c;那就是 GC 对象间的引用关系。不过光这么说可能大家还是不能理解&…

yolo人脸检测数据集_自定义数据集上的Yolo-V5对象检测

yolo人脸检测数据集计算机视觉 (Computer Vision) Step by step instructions to train Yolo-v5 & do Inference(from ultralytics) to count the blood cells and localize them.循序渐进的说明来训练Yolo-v5和进行推理(来自Ultralytics )以对血细胞进行计数并将其定位。 …

图深度学习-第2部分

有关深层学习的FAU讲义 (FAU LECTURE NOTES ON DEEP LEARNING) These are the lecture notes for FAU’s YouTube Lecture “Deep Learning”. This is a full transcript of the lecture video & matching slides. We hope, you enjoy this as much as the videos. Of cou…

Linux下 安装Redis并配置服务

一、简介 1、 Redis为单进程单线程模式&#xff0c;采用队列模式将并发访问变成串行访问。 2、 Redis不仅仅支持简单的k/v类型的数据&#xff0c;同时还提供list&#xff0c;set&#xff0c;zset&#xff0c;hash等数据结构的存储。 3、 Redis支持数据的备份&#xff0c;即mas…

leetcode 477. 汉明距离总和(位运算)

theme: healer-readable 题目 两个整数的 汉明距离 指的是这两个数字的二进制数对应位不同的数量。 计算一个数组中&#xff0c;任意两个数之间汉明距离的总和。 示例: 输入: 4, 14, 2 输出: 6 解释: 在二进制表示中&#xff0c;4表示为0100&#xff0c;14表示为1110&…

量子信息与量子计算_量子计算为23美分。

量子信息与量子计算On Aug 13, 2020, AWS announced the General Availability of Amazon Braket. Braket is their fully managed quantum computing service. It is available on an on-demand basis, much like SageMaker. That means the everyday developer and data scie…

全面理解Java内存模型

Java内存模型即Java Memory Model&#xff0c;简称JMM。JMM定义了Java 虚拟机(JVM)在计算机内存(RAM)中的工作方式。JVM是整个计算机虚拟模型&#xff0c;所以JMM是隶属于JVM的。 如果我们要想深入了解Java并发编程&#xff0c;就要先理解好Java内存模型。Java内存模型定义了多…