盖茨比乔布斯_使用wrapRootElement挂钩在盖茨比进行状态管理

盖茨比乔布斯

Since Gatsby handles our routes for us, that leaves us with nowhere to wrap our app with a Redux store or provider. In this article we’ll learn a clever trick to get around that.

由于Gatsby为我们处理了路线,因此我们无处可乘以Redux store或provider来包装我们的应用程序 。 在本文中,我们将学习解决此问题的巧妙技巧。

For the sake of simplicity, all of the examples will be using React’s Context API for our state management to save time from setting up boilerplate, but everything is still applicable to other state management methods. If you need to brush up on working with providers, you can check out this intro to the useContext hook.

为了简单起见,所有示例都将使用React的Context API进行状态管理,以节省设置样板的时间,但是所有内容仍然适用于其他状态管理方法。 如果您需要重新研究提供程序,可以查看useContext钩子的介绍

安装 (Installation)

I prefer to start with a very basic theme, but in the end we only need something with two pages so we can see that our state is being applied globally. Since we’ll be working with some styling I’ll add Sass support with node-sass and gatsby-plugin-sass, because I’m not an animal.

我更喜欢从一个非常基本的主题开始,但是最后我们只需要两页的内容,这样我们就可以看到我们的状态正在全球范围内应用。 由于我们将使用某些样式,因此我将通过node-sassgatsby-plugin-sass添加Sass支持,因为我不是动物。

$ gatsby new stateful-gatsby https://github.com/gatsbyjs/gatsby-starter-defaultCopyInstall
$ cd stateful-gatsby
$ yarn add node-sass gatsby-plugin-sass -D

与提供者包装 (Wrapping with Provider)

The first step is to setup our context provider with a simple isDark state and a method to reverse its current state. We’ll take whatever is passed-in as props and wrap it in our new myContext.Provider.

第一步是使用简单的isDark状态和反转其当前状态的方法设置上下文提供程序。 我们将传入的所有内容作为道具,并将其包装在新的myContext.Provider

provider.js
provider.js
import React, { useState } from 'react';

export const myContext = React.createContext();

const Provider = props => {
  const [isDark, setTheme] = useState(false);

  return (
    <myContext.Provider value={{
      isDark,
      changeTheme: () => setTheme(!isDark)
    }}>
      {props.children}
    </myContext.Provider>
  )
};

Just below it, we’ll export a function that’ll wrap whatever is passed to it in our new provider.

在它的正下方,我们将导出一个函数,该函数将在新的提供程序中包装传递给它的所有内容。

export default ({ element }) => (
  <Provider>
    {element}
  </Provider>
);

Now that we have a way to manage our state, Gatsby offers us a neat little hook called wrapRootElement, which you can check out in the docs. This hook takes most of our site and passes it as props into a function we give it, like the one we just exported from Provider.js, giving us the perfect little space to wrap everything inside.

现在我们有了一种管理状态的方法,盖茨比为我们提供了一个名为wrapRootElement小巧钩子,您可以在docs中检出它。 这个钩子占用了我们大部分的网站,并将其作为道具传递给我们提供的功能,就像刚从Provider.js导出的那个一样,为我们提供了一个完美的空间来将所有内容包装在里面。

Both gatsby-browser.js and gatsby-ssr.js have access to this hook and it’s recommended to wrap both with our provider, that’s why we defined the wrapper function in provider.js.

gatsby-browser.jsgatsby-ssr.js都可以访问此钩子,建议将它们都包装在我们的提供程序中,这就是为什么我们在provider.js定义了wrapper函数。

import Provider from './provider';

export const wrapRootElement = Provider;

造型 (Styling)

Here are our simple theme styles:

以下是我们的简单主题样式:

src/global.sass
src / global.sass
.colorTheme 
    height: 100vh
    transition: .3s ease-in-out

.darkTheme 
    @extend .colorTheme
    background-color: #1A202C
    color: #fff
    a
        color: yellow

.lightTheme 
    @extend .colorTheme
    background-color: #fff
    color: #000

应用主题 (Applying Themes)

The only thing we need to do to access our state is wrap each component in a myContext.Consumer and access our global state on context, React.Fragment is just to let us add more than one element.

访问状态的唯一要做的就是将每个组件包装在myContext.Consumer并在context上访问全局状态, React.Fragment只是为了让我们添加多个元素。

For our background color we can set our class conditionally to our state, if you had more than one theme you could set the provider’s theme as a string with our class name.

对于我们的背景色,我们可以有条件地将类设置为我们的状态,如果您有多个主题,则可以将提供者的主题设置为带有我们类名称的字符串。

layout.js
layout.js
import { myContext } from '../../provider';
import '../global.sass';

 return (
    <myContext.Consumer>
      {context => (
        <React.Fragment>
          <div className={context.isDark ? 'darkTheme' : 'lightTheme'}>
            {/* ... */}
          </div>
        </React.Fragment>
      )}
    </myContext.Consumer>
  )

We also have access to setTheme because we passed it to the changeTheme method. Let’s add a button to reverse isDark.

我们还可以访问setTheme因为我们将其传递给changeTheme方法。 让我们添加一个按钮来反转isDark

src/pages/index.js
src / pages / index.js
import { myContext } from '../../provider';

const IndexPage = () => (
  <Layout>
    <myContext.Consumer>
      {context => (
        <React.Fragment>
          <SEO title="Home" />
          <h1>{context.isDark ? "Dark Theme" : "Light Theme"}</h1>

          <button onClick={() => context.changeTheme()}>{context.isDark ? "Light" : "Dark"}</button>

          <Link to="/page-2/">Go to page 2</Link>
        </React.Fragment>
      )}
    </myContext.Consumer>
  </Layout>
);

Now if you add essentially the same configuration to page-2.js you should be able to change the state and move between them with the state remaining consistent between them.

现在,如果您向page-2.js添加基本​​相同的配置,则应该能够更改状态并在它们之间移动,而它们之间的状态保持一致。

page-2.js
page-2.js
import { myContext } from '../../provider';

const SecondPage = () => (
  <Layout>
    <myContext.Consumer>
      {context => (
        <React.Fragment>
          <SEO title="Page two" />
          <h1>{context.isDark ? "Dark Theme" : "Light Theme"}</h1>
          <p>Welcome to page 2</p>

          <button onClick={() => context.changeTheme()}>{context.isDark ? "Light" : "Dark"}</button>

          <Link to="/">Go back to the homepage</Link>
        </React.Fragment>
      )}
    </myContext.Consumer>
  </Layout>
);

Huzza! it’s really as simple as that, 3 small file changes and wrapping everything in a consumer and you’re good to go.

胡扎! 就这么简单,只需更改3个小文件并将所有内容包装在使用者中,您就可以开始了。

结论 (Conclusion)

For me, this wasn’t a very obvious way of doing things so I hope this was helpful in understanding how to use the wrapRootElement hook to your advantage.

对我来说,这不是很明显的处理方式,所以我希望这对理解如何利用wrapRootElement挂钩有帮助。

For the sake of convenience I’ve created a repo with this setup as a starter, which you can check out here.

为了方便起见,我已使用此设置作为启动器创建了一个存储库,您可以在此处查看

翻译自: https://www.digitalocean.com/community/tutorials/gatsbyjs-state-management-in-gatsby

盖茨比乔布斯

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值