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.pswp.cn/news/390847.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/390847.shtml
英文地址,請注明出處:http://en.pswp.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

html5語義化標記元素_語義HTML5元素介紹

html5語義化標記元素Semantic HTML elements are those that clearly describe their meaning in a human- and machine-readable way. 語義HTML元素是以人類和機器可讀的方式清楚地描述其含義的元素。 Elements such as <header>, <footer> and <article> …

重學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; 還是…

POJ 3660 Cow Contest [Floyd]

POJ - 3660 Cow Contest http://poj.org/problem?id3660 N (1 ≤ N ≤ 100) cows, conveniently numbered 1..N, are participating in a programming contest. As we all know, some cows code better than others. Each cow has a certain constant skill rating that is un…

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 如果這個網絡連接可達&…

JSON.parseObject(String str)與JSONObject.parseObject(String str)的區別

一、首先來說說fastjson fastjson 是一個性能很好的 Java 語言實現的 JSON 解析器和生成器&#xff0c;來自阿里巴巴的工程師開發。其主要特點是&#xff1a; ① 快速&#xff1a;fastjson采用獨創的算法&#xff0c;將parse的速度提升到極致&#xff0c;超過所有基于Java的jso…

jQuery Ajax POST方法

Sends an asynchronous http POST request to load data from the server. Its general form is:發送異步http POST請求以從服務器加載數據。 其一般形式為&#xff1a; jQuery.post( url [, data ] [, success ] [, dataType ] )url : is the only mandatory parameter. This…

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; 分別…

leetcode 1707. 與數組中元素的最大異或值

題目 給你一個由非負整數組成的數組 nums 。另有一個查詢數組 queries &#xff0c;其中 queries[i] [xi, mi] 。 第 i 個查詢的答案是 xi 和任何 nums 數組中不超過 mi 的元素按位異或&#xff08;XOR&#xff09;得到的最大值。換句話說&#xff0c;答案是 max(nums[j] XO…

MySQL基礎入門學習【2】數據類型

數據類型&#xff1a;指列、存儲過程參數、表達式和局部變量的數據特征&#xff0c;它決定了數據的存儲格式&#xff0c;代表了不同的信息類型 &#xff08;1&#xff09; 整型(按存儲范圍分類)&#xff1a;TINYINT&#xff08;1字節&#xff09; SAMLLINT&#xff08;2字節&am…

昆西·拉森的凈資產是多少?

People ask me how much I get paid all the time. It comes up on podcast interviews, Quora questions, and face-to-face discussions.人們問我&#xff0c;我一直得到多少報酬。 它來自播客訪談&#xff0c;Quora問題和面對面的討論。 And people search this question a…

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;無法為其高度優先…

Node.js umei圖片批量下載Node.js爬蟲1.00

這個爬蟲在abaike爬蟲的基礎上改改圖片路徑和下一頁路徑就出來了&#xff0c;代碼如下&#xff1a; // // umei圖片批量下載Node.js爬蟲1.00 // 2017年11月13日 //// 內置http模塊 var httprequire("http");// 內置文件處理模塊&#xff0c;用于創建目錄和圖片文件 v…

交通銀行信息技術管理部副總經理張漫麗:交通銀行“大數據+人工智能”應用研究...

文 | 交通銀行信息技術管理部副總經理張漫麗 大數據隱含著巨大的社會、經濟、科研價值&#xff0c;已引起了各行各業的高度重視。如果能通過人工智能技術有效地組織和使用大數據&#xff0c;將對社會經濟和科學研究發展產生巨大的推動作用&#xff0c;同時也孕育著前所未有的機…

安軟件一勞永逸_如何克服一勞永逸地公開演講的恐懼

安軟件一勞永逸If you’re like most people, the idea of public speaking terrifies you (it terrifies me too). So how do you get over those jitters, get up on stage, and give an amazing talk? First, a disclaimer: this article is purely about your stage prese…

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;盡管…