react銷毀方法鉤子0_React鉤子:使用React狀態的新方法

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

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/392833.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/392833.shtml
英文地址,請注明出處:http://en.pswp.cn/news/392833.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Linux下安全審計工具 lynis 使用說明

官網:https://cisofy.com/download/lynis/ 下載解壓后,執行./lynis -Q即可,稍等片刻自動生成一份檢測報告。可以根據檢測報告看哪里不足進行改進即可。 本文轉自 lirulei90 51CTO博客,原文鏈接:http://blog.51cto.com/…

課堂訓練

1.對于可能的變更是否能制定應急計劃? 可以制定 例如一款app的開發,在制作app之前會對app的功能性進行一個規劃,想的比較全面就能很好應對變更。 2.員工是否能夠有效地處理意料之外的工作請求? 能夠處理 對于工作能力極強的員工而…

Google 實用搜索技巧

孔子曰:“工欲善其事,必先利其器。居是邦也,是其大夫之賢者,友其示支仁者。”——語出《論語衛靈公》 1. Google搜索固定格式的文檔 Google支持特定格式文檔的搜索(“filetype:”就是它的搜索語法)&#xf…

華科的計算機和建筑學哪個強,華中科技大學和華南理工大學相比,誰更占優勢?看了也許就知道了...

大學是學生接受教育的過程中非常重要的一個階段,很多學生都會盡可能在高考中,考出更好的成績,爭取報考一個更好的大學。為了提升教育水平,我國到目前為止建設了超過3000所大學,其中有很多高等院校非常相似,…

c#+handle.exe實現升級程序在運行時自動解除文件被占用的問題

我公司最近升級程序經常報出更新失敗問題,究其原因,原來是更新時,他們可能又打開了正在被更新的文件,導致更新文件時,文件被其它進程占用,無法正常更新而報錯,為了解決這個問題,我花…

播客#50:Sacha Greif

On todays episode of the freeCodeCamp Podcast, Quincy Larson interviews Sacha Greif, a designer, developer, and prolific open source project creator.在今天的免費CodeCamp播客中,昆西拉爾森(Quincy Larson)采訪了設計師,開發人員和多產的開源…

leetcode 977. 有序數組的平方(雙指針)

給定一個按非遞減順序排序的整數數組 A,返回每個數字的平方組成的新數組,要求也按非遞減順序排序。 示例 1: 輸入:[-4,-1,0,3,10] 輸出:[0,1,9,16,100] 示例 2: 輸入:[-7,-3,2,3,11] 輸出&am…

Spring.net的一個小例子

入門級的Spring.net的例子,比Spring.net帶的例子還要簡單。容易上手。下載地址:http://files.cnblogs.com/elevenWolf/SpringTest.rar轉載于:https://www.cnblogs.com/martinxj/archive/2005/07/18/195105.html

使用JavaScript的Platformer游戲教程

Learn how to create a platformer game using vanilla JavaScript.了解如何使用香草JavaScript創建平臺游戲。 This tutorial starts with teaching how to organize the code using the Model, View, Controller (MVC) strategy and the principles of Object Oriented Prog…

leetcode 52. N皇后 II(回溯)

n 皇后問題研究的是如何將 n 個皇后放置在 nn 的棋盤上,并且使皇后彼此之間不能相互攻擊。 給定一個整數 n,返回 n 皇后不同的解決方案的數量。 示例: 輸入: 4 輸出: 2 解釋: 4 皇后問題存在如下兩個不同的解法。 [ [".Q…", // 解法 1 “……

uic計算機課程表,美國UIC大學研究生畢業率能達到多少?申請條件、專業課程匯總...

UIC大學也就是伊利諾伊大學芝加哥分校,這所學校始建于1982年,該校擁有東、西兩個校區,皆位于美國第二大商業中心芝加哥市的心臟地帶,地理位置優勢顯著,UIC大學有著豐富的教學資源和出色的教學水準,那么接下…

#region(C# 參考)

< DOCTYPE html PUBLIC -WCDTD XHTML StrictEN httpwwwworgTRxhtmlDTDxhtml-strictdtd> #region&#xff08;C# 參考&#xff09; #region 使您可以在使用 Visual Studio 代碼編輯器的大綱顯示功能時指定可展開或折疊的代碼塊。例如&#xff1a; #region MyClass defin…

java中常用的包、類、以及包中常用的類、方法、屬性----sql和text\swing

java中常用的包、類、以及包中常用的類、方法、屬性 常用的包 java.io.*; java.util.*; java.lang.*; java.sql.*; java.text.*; java.awt.*; javax.swing.*; 包名 接口 類 方法 屬性 java.sql.*; public class DriverManager extends Object static Connection…

Reindex SQL Server DB table

DBCCDBReindex(TableName,,90) Or ALTERINDEXALLONTableNameREBUILDWITH(FILLFACTOR90,SORT_IN_TEMPDBON,STATISTICS_NORECOMPUTEOFF,ONLINEOFF); 90 Refers to page density 90%, 10% is reserved for update. Show Index result by DBCCSHOWCONTIG 轉載于:https://www.cnblo…

cloudwatch監控_Amazon CloudWatch:無服務器日志記錄和監控基礎

cloudwatch監控Amazon CloudWatch is a monitoring and management service built for developers, system operators, site reliability engineers (SRE), and IT managers.Amazon CloudWatch是為開發人員&#xff0c;系統操作員&#xff0c;站點可靠性工程師(SRE)和IT經理構建…

電大計算機考試題目excel,電大計算機考試復習題EXCEL部分

電大計算機考試復習題001_prac2.xls(1) 將Sheet1工作表命名為dubug1.(2) 在debug1工作表中&#xff0c;試采用數據的填充功能分別填充A3;A30、B3&#xff1a;B30、C3&#xff1a;C30區域&#xff0c;前一區域中的前兩個單元格的內容為“10”和“11”&#xff0c;中間區域中的前…

leetcode 19. 刪除鏈表的倒數第N個節點(雙指針)

給定一個鏈表&#xff0c;刪除鏈表的倒數第 n 個節點&#xff0c;并且返回鏈表的頭結點。 示例&#xff1a; 給定一個鏈表: 1->2->3->4->5, 和 n 2. 當刪除了倒數第二個節點后&#xff0c;鏈表變為 1->2->3->5. 代碼 /*** Definition for singly-li…

Tegra3 vSMP架構Android運行時CPU熱插拔及高低功耗CPU切換

Tegra3采用vSMP&#xff08;VariableSymmetric Multiprocessing&#xff09;架構&#xff0c;共5個cortex-a9處理器&#xff0c;其中4個為高性能設計&#xff0c;1個為低功耗設計&#xff1a; 在系統運行過程中&#xff0c;會根據CPU負載切換低功耗處理器和高功耗處理器&#x…

Linux 內核總線

一個總線是處理器和一個或多個設備之間的通道. 為設備模型的目的, 所有的設備都通過 一個總線連接, 甚至當它是一個內部的虛擬的,"平臺"總線. 總線可以插入另一個 - 一個 USB 控制器常常是一個 PCI 設備, 例如. 設備模型表示在總線和它們控制的設備之間的 實際連接. …

leetcode 844. 比較含退格的字符串

給定 S 和 T 兩個字符串&#xff0c;當它們分別被輸入到空白的文本編輯器后&#xff0c;判斷二者是否相等&#xff0c;并返回結果。 # 代表退格字符。 注意&#xff1a;如果對空文本輸入退格字符&#xff0c;文本繼續為空。 示例 1&#xff1a; 輸入&#xff1a;S “ab#c”…