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

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 生命挂钩

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值