react上下文_基于React上下文的盖茨比全球状态管理

react上下文

Gatsby is a framework based on React to generate a website faster. So as you can imagine, a lot of problems can be handled in a “React” way. In this article, I am going to talk about how to deal with Gatsby’s state management with React’s context.

Gatsby是基于React的框架,可以更快地生成网站。 因此,您可以想像到,许多问题都可以通过“React”方式处理。 在本文中,我将讨论如何使用React的上下文处理Gatsby的状态管理。

我通常在React中做什么 (What I usually do in React)

Usually, if I want to grab a user object on every page in my website, in React, I will use componentDidMount to do that in my App.js like so:

通常,如果我想在网站的每个页面上抓取一个user对象,在React中,我将使用componentDidMountApp.js这样做, App.js所示:

//App.jsclass App extends React.Component {
componentDidMount() {
// do something to grab the User
fetchUser()// will grab the user and do something with that user page }
}

Since it is a single page application, all of other components are children to App, so we know that fetchUser is fired every single time the website is rendered, when App component is rendered.

由于它是一个单页面应用程序,因此所有其他组件都是App子组件,因此我们知道,呈现App组件时,每次呈现网站时都会触发fetchUser

But the problem is, there’s no such thing in Gatsby as the parent to all of other components. So we have to think about other ways to make it happen.

但是问题是,在盖茨比,没有其他所有组件的父对象。 因此,我们必须考虑实现该目标的其他方法。

处理盖茨比州的可能选择 (Possible options to deal with states in Gatsby)

There are a lot of ways to handle states in Gatsby. I prefer to use React’s Context to deal with it this time for many reasons, but I would still introduce what else you can use so you can use the one that fits your situation.

在盖茨比,有很多方法可以处理状态。 出于多种原因,我这次更喜欢使用React的Context进行处理,但是我仍然会介绍您可以使用的其他内容,以便可以使用适合您情况的内容。

分别处理状态 (Handle states separately)

Of course, you can always handle states separately in their own component. But it is going to cause a problem when you need to pass different props and state among various components frequently. That’s redundant and error-prone.

当然,您始终可以在各自的组件中分别处理状态。 但是当您需要经常在各个组件之间传递不同的道具和状态时,它将引起问题。 这是多余的并且容易出错。

Redux (Redux)

For people that use React, Redux might be familiar when coming to dealing with states. It is a cool tool to manage multiple states in your app that are communicated and mutated frequently among different components.

对于使用React的人,在处理状态时,Redux可能会很熟悉。 这是一个很酷的工具,可以管理您应用中的多个状态,这些状态在不同组件之间经常进行通信和变异。

However, I don’t want to use this on my Gatsby app because I am not handling too much global data. So I personally don’t want to set up everything for this library just to handle one user state. (In Gatsby, you need to install a plugin to use Redux).

但是,我不想在我的Gatsby应用程序上使用它,因为我不会处理太多的全局数据。 因此,我个人不想为该库设置所有功能只是为了处理一个user状态。 (在Gatsby中,您需要安装插件才能使用Redux)。

React上下文 (React Context)

I like Redux’s solution where you put all the global states in ONE place(“store” in Redux) and pull out the one you need when needed while I don’t have to do too much set up. If you are in the same situation, use React Context!

我喜欢Redux的解决方案,您可以将所有全局状态放在一个位置(在Redux中为“存储”),并在需要时取出所需的状态,而不必进行太多设置。 如果您处于相同情况,请使用 React Context

React上下文? (React Context?)

React context is built for solving this type of problem. Just like what is illustrated in the documentation:

React上下文是为解决此类问题而构建的。 就像文档中所示

In a typical React application, data is passed top-down (parent to child) via props, but this can be cumbersome for certain types of props (e.g. locale preference, UI theme) that are required by many components within an application. Context provides a way to share values like these between components without having to explicitly pass a prop through every level of the tree.

在典型的React应用程序中,数据是通过props自上而下(父级到子级)传递的,但这对于应用程序中许多组件所需的某些类型的props(例如,语言环境首选项,UI主题)可能会很麻烦。 上下文提供了一种在组件之间共享类似这些值的方法,而不必在树的每个级别上显式传递道具。

那怎么用呢? (How to use it, then?)

Try to think of context as a “store”, which stores all states you need to use among all different components. And when you need to use it, you just need to “go to the store”, and get the stuff you want.

尝试将上下文视为“存储”,其中存储了所有不同组件之间需要使用的所有状态。 而且,当您需要使用它时,您只需“去商店”,并获取所需的东西。

Ok, so you see there are two steps: store the data and get the data. I will explain to you how it is implemented in coding language.

好的,您将看到两个步骤: 存储数据和获取数据 。 我将向您解释如何以编码语言实现它。

商店在哪 (Where’s the store?)

A very simple truth: the store has to be somewhere that is reachable. If you are in Europe, it is not likely that you would go to a store in America, right? I mean, even you would for whatever reason, it is definitely not considered as “convenient”. So that is not what we want.

一个很简单的道理:商店必须位于可以到达的地方。 如果您在欧洲,就不太可能去美国的商店,对吗? 我的意思是,即使您出于任何原因也绝对不会将其视为“便利”。 所以这不是我们想要的。

So speaking of “reachable”, we can use Context.Provider to provide the data like this:

所以说到“可达”,我们可以使用Context.Provider提供这样的数据:

import React, { useState, createContext } from "react"export const UserStateContext = createContext(null)const Layout = ({ children }) => {
const [user, setUser] = useState()
console.log(user)...// do something to set or fetch the userreturn (
<UserStateContext.Provider value={user}>
<SEO />
<Navbar />
<main>{children}</main>
</UserStateContext.Provider>
)
}export default Layout

As you can see, first I create a context, and then I wrap up the components, where I want to use theuser object, with the context I just create, which is UserStateContext here. The user object is passed as the value prop at the same time.

如您所见,首先创建一个context ,然后包装我要在其中使用user对象的组件以及刚刚创建的上下文,这里是UserStateContextuser对象同时作为value prop传递。

Since I need a component that can be parent to all the components I need to use, I will use Layout component since I will use that on every page.

由于我需要的组件可以是我需要使用的所有组件的父组件,因此我将使用Layout组件,因为我将在每个页面上使用它。

如何访问数据? (How to access the data?)

Now I store data. How can I use that? The answer is Context.Consumer . Just like what I do with Provider, I should wrap up the EXACT component that I want to use the value, with Context.Consumer like so:

现在,我存储数据。 如何使用? 答案是Context.Consumer 。 就像我对Provider所做的一样,我应该使用Context.Consumer封装要使用该值的EXACT组件,如下所示:

const Dashboard = props => {       return (
<UserStateContext.Consumer>
{user => {
return user? <LoggedIn user={user} /> : <NotLoggedIn propertiesPassed={propertiesPassed}/>
}}
</UserStateContext.Consumer>

)
}

Once it is wrapped by <UserStateContext.Consumer>, I can use the value prop that is “stored” in my context. You can see that here:

一旦被<UserStateContext.Consumer>包装,我就可以使用上下文中“存储”的value prop。 您可以在这里看到:

{user => {
return user? <LoggedIn user={user} /> : <NotLoggedIn propertiesPassed={propertiesPassed}/>
}}

I name the prop as user when I extract that, and then control which component I should render using its value. But also, you can name it whatever you want!

提取道具时,我将该道具命名为user ,然后使用其值控制应渲染的组件。 而且,您可以随便命名!

Thanks for reading!

谢谢阅读!

翻译自: https://medium.com/swlh/gatsbys-global-state-management-with-react-s-context-5f8064e93351

react上下文

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值