react 生命掛鉤_如何在GraphQL API中使用React掛鉤來管理狀態

react 生命掛鉤

In this blog post, we are going to learn -

在這篇博客中,我們將學習-

  1. What React hooks are

    什么是React鉤子
  2. How to use hooks for state management

    如何使用掛鉤進行狀態管理

Before we start working with hooks, let us take a brief moment to talk about state management.

在開始使用鉤子之前,讓我們花一點時間討論狀態管理。

State management is managing data that flows between our application components. It could be data flowing inside one component (local state) or data flowing between multiple components (shared state). We need to manage state because sometimes components need to talk to each other through a reliable source of information. In Redux, this reliable source of information is called the store.

狀態管理正在管理在我們的應用程序組件之間流動的數據。 它可以是在一個組件內部流動的數據(本地狀態),也可以是在多個組件之間流動的數據(共享狀態)。 我們需要管理狀態,因為有時組件需要通過可靠的信息源相互通信。 在Redux中,這種可靠的信息源稱為存儲。

第1部分:React鉤子-什么和為什么 (Part 1: React hooks - the what and why)

什么是鉤子? (What are hooks?)

Hooks are functions that lets you access state without using a class component. Hooks are a more natural way of thinking about React. Instead of thinking of what lifecycle methods to use, you can now write components thinking about how and when your data needs to be used.

掛鉤是使您無需使用類組件即可訪問狀態的函數。 鉤子是思考React的一種更自然的方式。 現在,您無需考慮使用哪種生命周期方法,而可以編寫考慮如何以及何時使用數據的組件。

React hooks were introduced in October 2018 and released in February 2019. It is now available with React 16.8 and higher. React hooks became highly popular as soon as they were introduced.

React鉤子于2018年10月引入,并于2019年2月發布。它現在可用于React 16.8及更高版本。 引入后,React鉤子就變得非常流行。

  1. No boilerplate: To use hooks, you don't need to import any new libraries or write any boilerplate code. You can simply start using hooks out of the box in React 16.8 and up.

    沒有樣板:使用鉤子,不需要導入任何新庫或編寫任何樣板代碼。 您可以在React 16.8及更高版本中直接使用開箱即用的鉤子。
  2. No need to use class components to use state: Traditionally, if you were using a functional component and decided that this component needs React state, you would have to convert it into a React class component. With the addition of hooks, you can use React state inside a functional component.

    無需使用類組件來使用狀態:傳統上,如果您使用功能組件并確定該組件需要React狀態,則必須將其轉換為React類組件。 通過添加鉤子,可以在功能組件內部使用React狀態。
  3. More logical way of thinking of React: You no longer have to think about when React mounts a component and what you should do in componentDidMount and remember to clean it up in componentWillUnmount. Now you can think more directly about how data is consumed by your component. React takes care of handling the mounting and cleanup functions for you.

    您再也不用去想陣營坐騎當一個組件,哪些是你應該做的:發生React的思維更合乎邏輯的方式componentDidMount記得把它清理干凈的componentWillUnmount 。 現在,您可以更直接地考慮組件如何使用數據。 React會為您處理安裝和清理功能。

有哪些常見的鉤子? (What are some common hooks?)

1. useState (1. useState)

useState is used to set and update state like this.state in a class component.

useState用于在類組件中設置和更新類似this.state狀態。

const [ state, setState] = useState(initialState);

2. useEffect (2. useEffect)

useEffect is used to carry out a function that does side effects. Side effects could include things like DOM manipulation, subscriptions, and API calls.

useEffect用于執行產生副作用的功能。 副作用可能包括諸如DOM操作,訂閱和API調用之類的事情。

useEffect(() => {document.title = 'New Title' 
});

3. useReducer (3. useReducer)

useReducer works similar to how a reducer works in Redux. useReducer is used when state is more complex. You can actually use useReducer for everything you do with useState. It gives a dispatch function in addition to a state variable.

useReducer的工作方式與Redux中reducer的工作方式類似。 當狀態更復雜時使用useReducer。 實際上,您可以將useReducer用于useState的所有操作。 除了狀態變量外,它還提供了調度功能。

const [ state, dispatch ] = useReducer(reducer, initialArg, init);

4. useContext (4. useContext)

useContext is similar to the context API. In the context API, there is a Provider method and Consumer method. Similarly, with useContext, the closest Provider method is used to read data.

useContext與上下文API相似。 在上下文API中,有一個Provider方法和Consumer方法。 類似地,對于useContext,最接近的Provider方法用于讀取數據。

const value = useContext(MyContext);

For more detailed explanation of how each of these work, read the official docs.

有關這些功能的更多詳細說明,請閱讀官方文檔 。

第2部分:如何使用掛鉤進行狀態管理 (Part 2: How to use hooks for state management)

With React 16.8, you can use hooks out of the box.

使用React 16.8,您可以直接使用鉤子。

We are going to build an application to make a list of songs. Here is what it will do -

我們將構建一個應用程序來制作歌曲列表。 這是它的作用-

  1. Fetch a GraphQL API for a list of a songs and render it on the UI.

    提取GraphQL API以獲得歌曲列表,并將其呈現在UI上。
  2. Have the ability to add a song to the list.

    可以將歌曲添加到列表中。
  3. When the song gets added to the list, update the list on the frontend and store data on the backend.

    當歌曲被添加到列表中時,在前端更新列表并將數據存儲在后端。

By the way, all the code is available on my GitHub. To see this in action, you can go to this CodeSandbox.

順便說一下,所有代碼都可以在我的GitHub上找到 。 要查看實際效果,可以轉到此CodeSandbox 。

We are going to use the GraphQL API with this app, but you can do the following steps with a REST API as well.

我們將在此應用程序中使用GraphQL API,但您也可以使用REST API執行以下步驟。

步驟0:主要要點 (Step 0: Main gist)

The main idea here is that we are going to use context to pass data down to our components. We will be using hooks, useContext and useReducer, to read and update this state. We will be using useState to store any local state. For doing side effects such as calling an API, we are going to use useEffect.

這里的主要思想是我們將使用context將數據向下傳遞到我們的組件。 我們將使用鉤子useContextuseReducer來讀取和更新此狀態。 我們將使用useState來存儲任何本地狀態。 為了產生諸如調用API的副作用,我們將使用useEffect

Let's get started!

讓我們開始吧!

步驟1:設定內容 ( Step 1: Set up context)

import { createContext } from 'react';const Context = createContext({songs: []
});export default Context

步驟2:初始化您的狀態。 稱這個initialState (Step 2: Initialize your state. Call this initialState)

We are going to use this context from to initialize our state:

我們將使用from的上下文來初始化我們的狀態:

const initialState = useContext(Context);

步驟3:使用useReducer設置reducers (Step 3: Setup reducers using useReducer)

Now we are going to set up reducers with an initialState with useReducer in App.js:

現在,我們將在App.js中使用useReducer設置帶有initialState的reduceors:

const [ state, dispatch ] = useReducer(reducer, initialState);

步驟4:找出哪個是頂層組件。 (Step 4: Figure out which is the top level component.)

We will need to set up a Context Provider here. For our example, it will be App.js. Also, pass in the dispatch returned from useReducer here so that children can have access to dispatch:

我們將需要在此處設置一個上下文提供程序。 對于我們的示例,它將是App.js 另外,在此處傳遞useReducer返回的調度,以便子代可以訪問調度:

<Context.Provider value={state,dispatch}>// children components<App /><Context.Provider value={state,dispatch}>

步驟5:現在使用useEffect掛鉤連接API (Step 5: Now hook up the APIs using the useEffect hook)

const {state, dispatch} = useContext(Context);useEffect(() => {if(songs) {dispatch({type: "ADD_CONTENT", payload: songs});}}, [songs]);

步驟6:更新狀態 (Step 6: Update state)

You can use useContext and useReducer to receive and update global application state. For local state like form components, you can use useState.

您可以使用useContextuseReducer來接收和更新全局應用程序狀態。 對于表單組件之類的本地狀態,可以使用useState

const [artist, setArtist] = useState("");const [lyrics, setLyrics] = useState("");

And that's it! State management is now set up.

就是這樣! 現在建立了狀態管理。

Did you learn anything new? Have something to share? Tweet me on Twitter.

你學到新東西了嗎? 有東西要分享? 在Twitter上發給我。

翻譯自: https://www.freecodecamp.org/news/hooks-and-graphql/

react 生命掛鉤

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

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

相關文章

Linux第三周作業

1.三個法寶 ①存儲程序計算機工作模型&#xff0c;計算機系統最最基礎性的邏輯結構&#xff1b; ②函數調用堆棧&#xff0c;堆棧完成了計算機的基本功能&#xff1a;函數的參數傳遞機制和局部變量存取 &#xff1b; ③中斷&#xff0c;多道程序操作系統的基點&#xff0c;沒有…

什么時候使用靜態方法

問題&#xff1a;什么時候使用靜態方法 I am wondering when to use static methods? Say if I have a class with a few getters and setters, a method or two, and I want those methods only to be invokable on an instance object of the class. Does this mean I shou…

RESTful API淺談

2019獨角獸企業重金招聘Python工程師標準>>> 上半年時候&#xff0c;部門有組織的討論了一下實踐微服務的技術話題&#xff0c;主要內容是SOA服務和微服務各自的優勢和難點&#xff0c;其中有提到關于RESTful API設計方法。 正好最近在深入的學習HTTP協議&#xff0…

spring自動注入--------

<?xml version"1.0" encoding"UTF-8"?> <beans xmlns"http://www.springframework.org/schema/beans"xmlns:p"http://www.springframework.org/schema/p"xmlns:c"http://www.springframework.org/schema/c"xmlns…

變量的作用域和生存期:_生存分析簡介:

變量的作用域和生存期:In the previous article, I have described the Kaplan-Meier estimator. To give a quick recap, it is a non-parametric method to approximating the true survival function. This time, I will focus on another approach to visualizing a surviv…

數字孿生營銷_如何通過數字營銷增加您的自由職業收入

數字孿生營銷There are a lot of ways we could go with this topic as it’s a huge one, but I just want to cover the nuggets here and make it simple as well as practical to understand and implement.我們可以采用很多方法來處理這個主題&#xff0c;因為它是一個很大…

您的網卡配置暫不支持1000M寬帶說明

國內寬帶網速越來越快&#xff0c;運營商更是在今年初紛紛推進千兆寬帶業務。為了讓用戶更好地了解網絡狀況&#xff0c;360寬帶測速器發布新版&#xff0c;優化了寬帶測速范圍&#xff0c;可有效支持最高1000&#xff2d;的帶寬測量。此外&#xff0c;寬帶測速器能檢測用戶網卡…

教輔的組成(網絡流果題 洛谷P1231)

題目描述 蒟蒻HansBug在一本語文書里面發現了一本答案&#xff0c;然而他卻明明記得這書應該還包含一份練習題。然而出現在他眼前的書多得數不勝數&#xff0c;其中有書&#xff0c;有答案&#xff0c;有練習冊。已知一個完整的書冊均應該包含且僅包含一本書、一本練習冊和一份…

Java中怎么樣檢查一個字符串是不是數字呢

問題&#xff1a;Java中怎么樣檢查一個字符串是不是數字呢 在解析之前&#xff0c;怎么樣檢查一個字符串是不是數字呢 回答一 這些通常是由一個簡單的用戶自定義函數去解決的&#xff08;即&#xff0c;自帶的 “isNumeric” 函數&#xff09; 例如 public static boolean…

小程序支付api密鑰_如何避免在公共前端應用程序中公開您的API密鑰

小程序支付api密鑰問題 (The Problem) All you want to do is fetch some JSON from an API endpoint for the weather, some book reviews, or something similarly simple.您要做的就是從API端點獲取一些有關天氣的JSON&#xff0c;一些書評或類似的簡單內容。 The fetch qu…

永無止境_永無止境地死:

永無止境Wir befinden uns mitten in der COVID-19-Pandemie und damit auch im Mittelpunkt einer medialen Geschichte, die durch eine noch nie dagewesene Komplexitt und Dynamik gekennzeichnet ist. Wie kann Informationsdesign helfen, diese Explosion von Nachrich…

HDU4612 Warm up —— 邊雙聯通分量 + 重邊 + 縮點 + 樹上最長路

題目鏈接&#xff1a;http://acm.split.hdu.edu.cn/showproblem.php?pid4612 Warm up Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65535/65535 K (Java/Others)Total Submission(s): 7206 Accepted Submission(s): 1681 Problem DescriptionN planets are …

Android sqlite load_extension漏洞解析

路人甲 2015/09/25 14:540x01 sqlite load_extensionSQLite從3.3.6版本&#xff08;http://www.sqlite.org/cgi/src/artifact/71405a8f9fedc0c2&#xff09;開始提供了支持擴展的能力&#xff0c;通過sqlite_load_extension API&#xff08;或者load_extensionSQL語句&#xf…

去除Java字符串中的空格

問題&#xff1a;去除Java字符串中的空格 俺有一個像這樣的字符串 mysz "namejohn age13 year2001";我想要去除字符串里面的空格。我嘗試使用 trim() &#xff0c;但是呢它只去除了字符串前后的空格。我也嘗試用 ("\W", “”)&#xff0c;但是它把也給搞…

谷歌瀏覽器bug調試快捷鍵_Bug壓榨初學者指南:如何使用調試器和其他工具查找和修復Bug

谷歌瀏覽器bug調試快捷鍵As web developers, it often feels like we spend more time fixing bugs and trying to solve problems than we do writing code. In this guide well look at some common debugging techniques, so lets get stuck in.作為Web開發人員&#xff0c;…

吳恩達神經網絡1-2-2_圖神經網絡進行藥物發現-第1部分

吳恩達神經網絡1-2-2預測溶解度 (Predicting Solubility) 相關資料 (Related Material) Jupyter Notebook for the article Jupyter Notebook的文章 Drug Discovery with Graph Neural Networks — part 2 圖神經網絡進行藥物發現-第2部分 Introduction to Cheminformatics 化學…

再利用Chakra引擎繞過CFG

xlab 2015/12/24 15:00Author:[email protected]0x00 前言本文源自一次與TK閑聊&#xff0c;期間得知成功繞過CFG的經過與細節(參考&#xff1a;[利用Chakra JIT繞過DEP和CFG])。隨即出于對技術的興趣&#xff0c;也抽出一些時間看了相關的東西&#xff0c;結果發現了另一處繞…

論文搜索源

中國科學院文獻情報中心 見下圖 中國計算機學會推薦國際學術會議和期刊目錄 EI學術會議中心,        engieer village 轉載于:https://www.cnblogs.com/cxy-941228/p/7693097.html

重學TCP協議(10)SYN flood 攻擊

1.SYN flood 攻擊 SYN Flood&#xff08;半開放攻擊&#xff09;是一種拒絕服務&#xff08;DDoS&#xff09;攻擊&#xff0c;其目的是通過消耗所有可用的服務器資源使服務器不可用于合法流量。通過重復發送初始連接請求&#xff08;SYN&#xff09;數據包&#xff0c;攻擊者能…

大數據入門課程_我根據數千個數據點對互聯網上的每門數據科學入門課程進行了排名...

大數據入門課程by David Venturi大衛文圖里(David Venturi) A year ago, I dropped out of one of the best computer science programs in Canada. I started creating my own data science master’s program using online resources. I realized that I could learn everyt…