react 生命挂钩_简而言之,React useContext挂钩

news/2024/7/7 10:09:51

react 生命挂钩

Early February 2019, React introduced Hooks as a way to rewrite your components as simple, more manageable, and classless. useContext is one of the built-in Hooks, giving functional components easy access to your context. But before we dive into useContext, first some context (pun intended! 🙈).

2019年2月上旬,React引入了Hooks ,以一种将您的组件重写为简单,易于管理和无类的方式。 useContext是内置的Hook之一,使功能组件可以轻松访问上下文。 但是,在我们进入useContext之前,首先要了解一些上下文(双关语!)。

The React Context API is a simple, easy-to-understand alternative to “prop-drilling” up and down your component tree. Instead of passing local data around and through several layers of components, it takes a step back to create global state, which is extremely useful for data that needs to be shared across components (data such as themes, authentication, preferred language, etc.)

React Context API是一种简单,易于理解的替代方法,可以在组件树中上下“ prop-drill”。 与其将本地数据传递到多层组件周围或不通过多层组件,而是回退到创建全局状态,这对于需要在各个组件之间共享的数据(主题,身份验证,首选语言等数据)非常有用。

Before Hooks came along, you would need to use class-based components. Class components could manage local state or give you the ability to pass updates back to your state-management. In a class-based component, you could set up a contextType or a <Consumer> and access your global state passed down from a provider. But now React has switched to light-weight, functional components and if you’re here, you probably want to do the same.

在Hooks出现之前,您需要使用基于类的组件。 类组件可以管理本地状态,或者使您能够将更新传递回状态管理。 在基于类的组件中,您可以设置contextType<Consumer>并访问从提供程序传递过来的全局状态。 但是现在React已经改用轻巧的功能组件,如果您在这里,您可能想要这样做。

With functional components, we have an elegant, readable component. In the past, functional components were nice to use, since they were less verbose, but they were quite limited to only really receiving props and rendering a UI based on those props. With Hooks we can manage everything we had used class-based components for.

有了功能组件,我们有了一个优雅,易读的组件。 过去,功能组件很好用,因为它们不太冗长,但它们仅限于仅真正接收道具并基于这些道具渲染UI。 使用Hooks,我们可以管理使用基于类的组件的所有内容。

示例上下文 (Example Context)

Let’s take a look at how to access context with the useContext Hook. First, a simple store for our example:

让我们看一下如何使用useContext Hook访问上下文。 首先,为我们的示例提供一个简单的存储:

const colors = {
  blue: "#03619c",
  yellow: "#8c8f03",
  red: "#9c0312"
};

export const ColorContext = React.createContext(colors.blue);

提供上下文 (Provide Context)

Then, we can provide our context to whatever branch needs it. In this instance, we create colors for the entire app, so we will wrap it in our App:

然后,我们可以需要的任何分支提供上下文。 在这种情况下,我们为整个应用程序创建颜色,因此我们将其包装在我们的App

import { ColorContext } from "./ColorContext";

function App() {
  return (
    <ColorContext.Provider value={colors}>
      <Home />
    </ColorContext.Provider>
  );
}

This provides the context to the rest of the component (represented by the Home component). No matter how far a component is away from the Home component, as long as it is somewhere in the component tree, it will receive the ColorContext. There are various ways of consuming our context in any component wrapped with our provider.

这为其余组件(由Home组件表示) 提供了上下文。 不管组件离Home组件有多远,只要它在组件树中的某个位置,它都会收到ColorContext 。 在我们的提供程序包装的任何组件中,都有多种使用我们的上下文的方式。

消费环境 (Consume Context)

We can use <Consumer> which is available in both class-based and functional components. It would look something like this to use in your JSX:

我们可以使用<Consumer> ,它在基于类的组件和功能组件中都可用。 在您的JSX中使用的外观如下所示:

return (
  <ColorContext.Consumer>
    {colors => <div style={colors.blue}>...</div>}
  </ColorContext.Consumer>
);

Yet, consuming our context this way is only available in the return block so can’t be accessed outside of your JSX code. Of course, there are workarounds, but it isn’t going to be the most ideal.

但是,以这种方式使用我们的上下文仅在return块中可用,因此无法在您的JSX代码之外进行访问。 当然,有解决方法,但这并不是最理想的。

You can give your component a context type: MyComponent.contextType = ColorContext; then, you can access the context in your component: let context = this.context; and that allows you to access your context outside of the JSX. Or instead, you could put in static contextType = ColorContext;. This works pretty good for class-based components, since it simplifies how to bring your context into your component. But, it will not work in a functional component.

您可以为您的组件提供上下文类型: MyComponent.contextType = ColorContext; 然后,您可以访问组件中的上下文: let context = this.context; 这样您就可以在JSX之外访问上下文。 或者,您可以放入static contextType = ColorContext; 。 这对于基于类的组件非常有效,因为它简化了将上下文引入组件的方法。 但是,它不能在功能组件中工作。

输入useContext (Enter useContext)

useContext is the same as static contextType = ColorContext, except that it’s for a functional component. At the top of your component, you can use it like this:

useContext与static contextType = ColorContext相同,区别在于它用于功能组件。 在组件的顶部,您可以像这样使用它:

import React, { useContext } from "react";

const MyComponent = () => {
  const colors = useContext(ColorContext);

  return <div style={{ backgroundColor: colors.blue }}>...</div>;
};

Now your component is simple, easy to read, and easy to test. useContext is as simple as that 🤓. Make sure here that you aren’t passing ColorContext.Consumer to useContext, we want the entire context here, not the provider or consumer. Also, instead of wrapping your JSX in a Consumer, you no longer need to in order to access your context. useContext will do that for you.

现在,您的组件变得简单,易于阅读且易于测试。 useContextuseContext简单。 确保此处没有将ColorContext.Consumer传递给useContext,我们需要此处的整个上下文,而不是提供者或使用者。 同样,您也不必为了将JSX包装在使用者中而访问上下文。 useContext将为您做到这一点。

参考 (Reference)

As with all of the new Hooks, they aren’t necessarily anything new. They follow the same React patterns we have previously learned. For more information on the Hooks, see the official docs.

与所有新的Hook一样,它们不一定是新的。 它们遵循我们先前学习的相同React模式。 有关挂钩的更多信息,请参见官方文档 。

翻译自: https://www.digitalocean.com/community/tutorials/react-usecontext

react 生命挂钩


http://www.niftyadmin.cn/n/3649275.html

相关文章

OkHttp3的使用

一、首先需要Gradle,GitHub的链接:http://square.github.io/okhttp/ compile com.squareup.okhttp3:okhttp:3.9.0 二、测试get方法 /*** 测试get方法*/ Test public void testGet() {//创建OKHttpClient对象OkHttpClient okHttpClient new OkHttpClient();//创建request对象Re…

Android 使用Fragment,ViewPagerIndicator 开发APP项目的主框架

本来准备下载个CSDN的客户端放手机上&#xff0c;没事可以浏览浏览资讯&#xff0c;下载了官方的之后&#xff0c;发现并不能很好的使用。恰好搜到一个大神自己写的csdn的app&#xff0c;下载安装了一下&#xff0c;感觉很不错&#xff0c;也很流畅&#xff0c;基本满足了我们 …

spread运算符_JavaScript中的Spread运算符有什么用?

spread运算符Learn about the ES6 spread operator, and some practical uses for this powerful JavaScript feature! 了解ES6传播运算符&#xff0c;以及此强大JavaScript功能的一些实际用法&#xff01; The spread operator is a feature of JavaScript introduced with E…

E测中国翻译团队成立,首战告捷!

应广大网友的热烈要求&#xff0c;E测翻译小组正式成立&#xff0c;对外宣传的E测翻译团队首页&#xff1a;https://sites.google.com/site/5etestingtranslating/home 说明&#xff1a;E测翻译团队为E测中国&#xff08;www.5etesting.com&#xff09;旗下的翻译团队&#xf…

基于MVP架构的OKHttp3的封装

一、OKHttp的优势 url测试地址&#xff1a;http://httpbin.org 二、首先对Response进行封装 ①定义IResponse接口 public interface IResponse {//状态码int getCode();//数据体String getData(); } ②BaseResponse实现继承IResponse public class BaseResponse implements …

《QTP项目应用与进阶》发布啦 - 自动化测试从业人员的必备宝典!!!

真高兴&#xff0c;书籍就快要上市了 百度百科&#xff1a;http://baike.baidu.com/view/2772580.htm 当当网&#xff1a;http://product.dangdang.com/product.aspx?product_id20686980&】 卓越亚马逊&#xff1a;http://www.amazon.cn/QTP%E9%A1%B9%E7%9B%AE%E5%BA%9…

[_NET]如何让Win2000和XP SP1支持System.EnterpriseServices(未验证)

有的地方写System.EnterpriseServices可以在WinXPSP2和Win2003上使用&#xff0c;我们可以让Win2000和WinXPSP1上也可以使用。引子&#xff1a;我在WinXP Pro上和Win2000上都无法运行下面语句&#xff1a;sc new System.EnterpriseServices.ServiceConfig();总是得到 ex.Messa…

摆动排序 II · Wiggle Sort II

链接&#xff1a; 题解&#xff1a; 1.先用partition函数&#xff0c;求得n/2的位置的排序 2.然后选取首尾指针&#xff08;奇数选择1和length-1&#xff0c;偶数选择为1和length-2&#xff09;&#xff0c;进行swap交换 3.每次首指针每次2&#xff0c;尾指针每次-2 九章算…