react上下文_了解React的新上下文API

react上下文

介绍 (Introduction)

In a world where there are lots of different front-end frameworks, it’s always hard to know which one to pick. Do I want to use the ever popular Angular? Or would diving into VueJS be beneficial to my scope of knowledge?

在存在许多不同的前端框架的世界中,总是很难知道该选择哪个框架。 我要使用广受欢迎的Angular吗? 还是进入VueJS会对我的知识范围有所帮助?

Then we have ReactJS, a framework created by Facebook that seems to be taking the front-end framework world by storm. Using components, a virtual DOM, and JSX (that’s for a different day!), React seems to cover it all, making it a powerful framework.

然后我们有了ReactJS,这是由Facebook创建的框架,似乎正在席卷前端框架世界。 通过使用组件,虚拟DOM和JSX(这是另一天的事情!),React似乎涵盖了所有内容,使其成为一个强大的框架。

The new Context API was recently introduced in React 16.3 as:

新的Context API最近在React 16.3中引入为:

A way to pass data through the component tree without having to pass props down manually at every level

一种通过组件树传递数据而无需在每个级别手动传递道具的方法

Sounds great! Let’s dig in.

听起来不错! 让我们深入。

道具与状态 (Props and State)

In React, you have props and state. Two very important things to understand.

在React中,您有propsstate 。 要理解的两个非常重要的事情。

Props, short for properties, is the data that is getting passed to the component from a parent component.

道具 (Properties)是属性的缩写,是从父组件传递到组件的数据。

State is data that is being managed within the component. So if each component has it’s own state, how do we share that information to another component? You could use props, but props can only be passed between parent and child components.

状态是在组件内管理的数据。 因此,如果每个组件都有其自己的状态,我们如何将信息共享给另一个组件? 您可以使用道具,但是道具只能在父组件和子组件之间传递。

So what are we to do if we have many layers of components to pass just one bit of information? Also known as, prop-drilling?

那么,如果我们有许多层的组件仅传递一点信息,该怎么办? 也称为Struts钻?

道具钻探(Context API解决了什么) (Prop Drilling (What the Context API Solves))

Let’s take a look at an example of prop-drilling so we can understand what the Context API is solving. In this example, we will see how we can pass information from one component, to the child component, then to that component’s child.

让我们看一下prop-drilling的示例,以便我们可以了解Context API所要解决的问题。 在此示例中,我们将看到如何将信息从一个组件传递到子组件,再传递到该组件的子组件。

const Lowest = (props) => (
  <div className="lowest">{props.name}</div>
)

const Middle = (props) => (
  <div className="middle">
    <Lowest name={props.name} />
  </div>
)

class Highest extends Component {
  state = {
    name: "Context API"
  }

  render() {
    return  <div className="highest">
      {this.state.name}
      <Middle name={this.state.name} />
    </div>
  }
}

I know the naming isn’t the most real-world, but it helps to demonstrate context’s ability to pass down to nested components. A more real-world scenario is one that may happen within a card-based user interface: CardGrid -> CardContent -> CardFooter -> LikeButton.

我知道命名不是最真实的,但是它有助于证明上下文传递给嵌套组件的能力。 一种更现实的情况是在基于卡的用户界面中可能发生的情况: CardGrid > CardContent > CardFooter > LikeButton

Back to our example, this is how those Highest -> Middle -> Lowest components would get nested:

回到我们的示例,这就是嵌套那些Highest -> Middle -> Lowest组件的方式:

<Highest>

    <Middle>

        <Lowest>

            {/* we want our content here but dont want to prop pass ALLLL the way down ! */}

        </Lowest>

    </Middle>

</Highest>

Notice how in order for the Highest and the Lowest to talk, they need the Middle to be the messenger?

注意,为了使最高和最低的通话方式,他们需要中间人作为使者?

Well lo and behold, we have React Context that can take care of all the work for us.

好吧,瞧瞧,我们有React Context可以为我们处理所有工作。

React的Context API (React’s Context API)

React Context allows us to have a state that can be seen globally to the entire application.

React Context允许我们拥有一个可以在整个应用程序中全局看到的状态。

We have to start with the context provider (<Provider />) to define the data you want to be sending around and you need the context consumer (<Consumer />) that grabs that data and uses it where called.

我们必须从上下文提供程序( <Provider /> )开始定义要发送的数据,并且需要上下文使用者( <Consumer /> )来获取数据并在调用时使用它。

With Context, you now have the ability to declare the state once, and then use that data, via the context consumer, in every part of the application.

使用上下文,您现在可以声明一次状态,然后通过上下文使用者在应用程序的每个部分中使用该数据。

Sounds incredible, right? Well let’s look at how we could set that up in a simple React application.

听起来不可思议,对吧? 好吧,让我们看看如何在一个简单的React应用程序中进行设置。

Let’s build!

让我们开始吧!

使用Context API构建名称传输 (Building a Name Transfer with Context API)

Today we are going to be setting up a basic React app. Let’s do an app that passes a name from one component to another component that just so happens to not be the child component! Great! We will have three different levels, one will be the highest component that has the name stored in state, we will have the middle component, and then we’ll have the lowest component.

今天,我们将要建立一个基本的React应用程序。 让我们做一个应用程序,它将名称从一个组件传递到另一个组件,而恰好不是子组件! 大! 我们将分为三个不同的级别,一个是将状态存储在状态中的最高级别的组件,一个将是中间的组件,然后是最低的组件。

Our application will send the name in state from the highest to the lowest without having to talk to the middle. Open up whichever code editor you like to use and let’s start coding!

我们的应用程序将以最高到最低的状态发送名称,而无需与中间人员交谈。 打开您要使用的任何代码编辑器,然后开始编码!

First, we will need the react dependency for our app. Go ahead and add that to your dependencies or if you are working in a text editor, do the following steps to install it:

首先,我们将需要应用程序的react依赖关系。 继续并将其添加到您的依赖项中,或者如果您正在使用文本编辑器,请执行以下步骤来安装它:

  1. Install npm globally on your machine if you do not already have it.

    如果尚未在计算机上全局安装npm。
  2. npm install —save react

    npm install —save react

  3. Check your package.json for the react dependency.

    检查您的package.json是否有react依赖关系。

In our main .js file, this is where the magic happens. Whenever we are building a React app, you always need to import your dependencies, otherwise that file won’t know to use it. So at the top of the index.js file, let’s import what we need:

在我们的主要.js文件中,神奇的地方就在这里。 每当我们构建React应用程序时,您总是需要导入您的依赖项,否则该文件将不会使用。 因此,在index.js文件的顶部,让我们导入所需的内容:

import React, { Component } from 'react';

We have our import, now let’s move on to the component. We will want to declare our context in a variable for readability. Under our import let’s do:

我们已经导入了,现在让我们继续该组件。 为了便于阅读,我们将在变量中声明上下文。 在我们的导入下,我们可以执行以下操作:

const AppContext = React.createContext()

我们的组件层 (Our Layers of Components)

Our Highest component will have the state. Our state will have a name that we will want to pass to the Lowest component without having to talk to the Middle component:

我们的Highest组件将具有状态。 我们的州将有一个名称,我们希望将其传递给Lowest组件而不必与Middle组件进行对话:

class Highest extends Component {
    state = {
        name : “React Context API”,
    }

    render() {
        return ( 
        <AppContext.Provider value={this.state}>
          {this.props.children}
        </AppContext.Provider>
        )
    }
}

We will build our child component to that calling it the Middle component:

我们将构建称为“ Middle组件的子组件:

const Middle = () => (
  <div>
    <p>I’m the middle component</p>
    <Lowest />
  </div>
)

And the child component to that will be called Lowest:

子组件将被称为Lowest

const Lowest = () => (
  <div>
     <AppContext.Consumer>
        {(context) => context.name}
      </AppContext.Consumer>
  </div>
)

Let’s go over this. You will see that we have a state in Highest that we will want to pass to Lowest. We have our static property that will allow us to declare what we want our context to be. In our case, the name “React Context API”.

让我们来看一下。 您将看到我们处于“ Highest状态,我们希望将其传递给“ Lowest 。 我们有我们的静态属性 ,它将使我们能够声明我们想要的上下文是什么。 在我们的例子中,名称为“React上下文API”。

The Provider is holding on to that data so that when it’s consumed by another component, it knows what to give it. In our Lowest component you will see that we have the Consumer wanting that data without having to first pass it to the Middle component. That component instead just hangs out, declaring that Lowest is it’s child.

Provider是坚持到数据,以便当它consumed另一个组件,它知道如何给它。 在我们的Lowest组件中,您将看到我们有Consumer想要该数据,而不必先将其传递给Middle组件。 该组件只是挂出,声明Lowest是它的孩子。

何时不使用上下文 (When to Not Use Context)

For a simple prop drilling solution that can scale decently, give context a go! For larger scale apps that have multiple (and more complex) states, reducers, etc, Redux may be a better fit.

对于可以适当扩展的简单的支撑钻探解决方案,请尝试一下! 对于具有多个(和更复杂)状态,reducer等的大型应用程序,Redux可能更合适。

There is no need to use context all over your application making things a little too messy. Be resourceful with your code, do not just use context to skip extra typing.

无需在整个应用程序中使用上下文,这会使事情变得有些混乱。 充分利用代码,不要仅仅使用上下文来跳过额外的输入。

结论 (Conclusion)

The React Context API is pretty awesome. But don’t use it unless you know it will be beneficial to you and your code. Redux might be just fine. Stay away from prop drilling and know that something like context can help you avoid that. It’s a great alternative!

React Context API非常棒。 但是除非您知道它将对您和您的代码都有益,否则不要使用它。 Redux可能很好。 远离道具钻,并知道类似上下文的内容可以帮助您避免这种情况。 这是一个很好的选择!

If you want to check out all the code, you can get it all on codesandbox.

如果要签出所有代码,可以在codesandbox上获取所有代码

翻译自: https://www.digitalocean.com/community/tutorials/get-to-know-reacts-new-context-api

react上下文

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值