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.mzph.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…