gatsby_为Gatsby网站元数据创建自定义React挂钩

gatsby

钩啊! (Hooks ahoy!)

Ok, let's get it on with the new hotness in Reactland, React Hooks!This is a guide covering using the Gatsby custom React hook forStaticQuery which it is now replacing with useStaticQuery.

好的,让我们继续使用Reactland中的新功能React Hooks!这是一本指南,涵盖了如何使用Gatsby自定义React钩子来实现StaticQuery ,现在它已被useStaticQuery取代。

If you haven't used Gatsby before StaticQuery is just that, a way toquery data in a Gatsby component (i.e. a react component) or a Gatsbypage where the query input doesn't change. This is a great use casefor data that doesn't change a great deal, like your site metadata.

如果在StaticQuery之前还没有使用过Gatsby, StaticQuery是一种查询Gatsby组件(即react组件)或Gatsbypage中数据的方法,查询输入不变。 这是一个很好的用例,用于数据不会发生很大变化的数据,例如您的网站元数据。

tl; dr (tl;dr)

Here's me trying to even with codesandbox.io whilst I convert someof the Gatsby default starter that's on codesandbox.io to use theuseSiteMetadata custom hook.

这里就是我想即使codesandbox.io虽然我转换someof盖茨比默认启动这对codesandbox.io使用useSiteMetadata定制挂钩。

Using codesandbox.io we take a look at implementing a custom reacthook for getting site metadata in Gatsby.

通过使用codesandbox.io,我们来看看实现自定义reacthook以便在Gatsby中获取站点元数据。

Here's a video:

这是一个视频:

The StaticQuery component uses the render props pattern, whichmeans it takes in a function and returns/renders based off of that.

StaticQuery组件使用render props模式,这意味着它接受了一个函数并根据该函数返回/渲染。

I have detailed this pattern before in a post about using the reactcontext api, it's a component that you pass a function to, to rendera component.

在关于使用react context api的帖子中,我已经详细介绍了这种模式,它是您将函数传递给rendera组件的组件。

Think of it like this:

这样想:

<Component>
 {() => ()}
</Component>

The first parenthesis is the arguments/variables and the second iswhat gets rendered, so in the case of the Gatsby StaticQuery youpass a query with a graphql tag and then the data that comes backfrom that is what is used in the render of that component. So you haveyour wrapping component that returns and renders a child component,like this.

第一个圆括号是参数/变量,第二个圆括号是要呈现的内容,因此在Gatsby StaticQuery的情况下, StaticQuery传递带有graphql标记的查询,然后从返回的data中返回用于该组件呈现的数据。 因此,您需要使用包装组件返回并呈现一个子组件,如下所示。

<WrappingComponent>
  {args => <ComponentToRender propsForComponent={args.propNeeded} />}
</WrappingComponent>

Here's a cut down version of the StaticQuery component being used inthe Gatsby default starter on codesandbox.io

这里有一个切下来的版本StaticQuery组件被用来在矿井上的盖茨比默认启动codesandbox.io

I've taken out the styling to make it a bit shorter:

我把样式弄短了一点:

const Layout = ({ children }) => (
  <StaticQuery
    query={graphql`
      query SiteTitleQuery {
        site {
          siteMetadata {
            title
          }
        }
      }
    `}
    render={data => (
      <>
        <Header siteTitle={data.site.siteMetadata.title} />
        <div>
          <main>{children}</main>
          <footer />
        </div>
      </>
    )}
  />
);

export default Layout;

The StaticQuery takes in two props, the query and what you want torender with render, this is where you can destructure the data youneed out of the data prop returned from the query.

StaticQuery两个StaticQuery ,即query和要使用render属性,在这里您可以从查询返回的data属性中解构所需的数据。

I was never really a fan of doing it that way so I adopted a similarpattern but with the component contained on it's own and then added tothe StaticQuery separately. Like this:

我从来都不是真正喜欢这样做的人,所以我采用了类似的模式,但是组件本身包含了该组件,然后将StaticQuery单独添加到StaticQuery 。 像这样:

const Layout = ({ children, data }) => (
  <>
    <Header siteTitle={data.site.siteMetadata.title} />
    <div>
      <main>{children}</main>
      <footer />
    </div>
  </>
);

export default props => (
  <StaticQuery
    query={graphql`
      query SiteTitleQuery {
        site {
          siteMetadata {
            title
          }
        }
      }
    `}
    render={data => <Layout data={data} {...props} />}
  />
);

I found this more acceptable because you didn't have to have all thecode bunched into the StaticQuery component.

我发现这更可接受,因为您不必将所有代码都StaticQueryStaticQuery组件中。

That all make sense?

都说得通吗?

Good, now forget about all of that! It's time to use the newuseStaticQuery hotness in Gatsby. ?

很好,现在就算了! 现在该在Gatsby中使用新的useStaticQuery了。 ?

版本: (Versions:)

This guide is being used with the following dependency versions.

本指南与以下依赖项版本一起使用。

  • gatsby: 2.1.31

    盖茨比:2.1.31
  • react: 16.8.4

    React:16.8.4
  • react-dom: 16.8.4

    React区:16.8.4

You can also check out the example code.

您还可以查看示例代码



The Gatsby documentation covers the use of it and also how to makeyour own custom react hook to use useStaticQuery, here's the one Iuse in the video.

Gatsby文档涵盖了它的用法,以及如何使自己的自定义react钩子使用useStaticQuery ,这是视频中的Iuse。

useSiteMetadata.js

useSiteMetadata.js

import { graphql, useStaticQuery } from 'gatsby';

const useSiteMetadata = () => {
  const { site } = useStaticQuery(
    graphql`
      query SITE_METADATA_QUERY {
        site {
          siteMetadata {
            title
            description
            author
          }
        }
      }
    `
  );
  return site.siteMetadata;
};

export default useSiteMetadata;

This can now be implemented in the rest of the code as a functioncall:

现在,可以在其余代码中将其作为函数调用实现:

const { title, description, author } = useSiteMetadata();

让我们实现它! (Let's implement it!)

In the layout component import the useSiteMetadata hook then wecan go about removing the StaticQuery component and destructuringtitle from the useSiteMetadata hook.

layout组件中,导入useSiteMetadata挂钩,然后我们可以删除StaticQuery组件,并从useSiteMetadata挂钩中解构title

It should look something like this, I have taken the styling out forbrevity:

它应该看起来像这样,我已经简洁了:

import React from 'react';
import PropTypes from 'prop-types';
import useSiteMetadata from './useSiteMetadata';

import Header from './header';
import './layout.css';

const Layout = ({ children }) => {
  const { title } = useSiteMetadata();
  return (
    <>
      <Header siteTitle={title} />
      <div>
        <main>{children}</main>
        <footer>
          © {new Date().getFullYear()}, Built with
          {` `}
          <a href="https://www.gatsbyjs.org">Gatsby</a>
        </footer>
      </div>
    </>
  );
};
Layout.propTypes = {
  children: PropTypes.node.isRequired,
};

export default Layout;

Here's the comparison:

比较如下:

On now to the seo component, same again, remove StaticQuery anduse useSiteMetadata in it's place.

现在,再次对seo组件进行删除,删除StaticQuery useSiteMetadata在其位置使用useSiteMetadata

Here's the comparison:

比较如下:

If you want to check out the code the example is available here:example code

如果您想查看代码,可以在以下示例中找到示例代码:

结语! (Wrap up!)

That's it! Wh have gone from using the awesome StaticQuery renderprops pattern used in Gatsby over to the even more awesomeuseStaticQuery React hooks, hook.

而已! 从使用Gatsby中令人敬畏的StaticQuery renderprops模式转变为更加令人敬畏的useStaticQuery React钩子hook。

Thanks for reading ?

感谢您阅读

Please take a look at my other content if you enjoyed this.

如果喜欢的话,请看看我的其他内容。

Follow me on Twitter or Ask Me Anything on GitHub.

Twitter上关注我,或在GitHub上询问我

You can read other articles like this on my blog.

您可以在我的博客上阅读其他类似的文章

翻译自: https://www.freecodecamp.org/news/creating-a-custom-react-hook-for-gatsby-site-metadata/

gatsby

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值