【发布时间】:2021-08-18 02:27:19
【问题描述】:
我想在包含路径名的 body 标记中添加一个类。 我认为我应该可以访问 location 道具,并且我应该能够通过它。 但是位置被传递为空。
我将其用作资源:https://www.gatsbyjs.com/docs/location-data-from-props/
/**
* SEO component that queries for data with
* Gatsby's useStaticQuery React hook
*
* See: https://www.gatsbyjs.org/docs/use-static-query/
*/
import React from "react"
import PropTypes from "prop-types"
import Helmet from "react-helmet"
import { useStaticQuery, graphql } from "gatsby"
const SEO = ({ description, lang, meta, title, location }) => {
const mylocation = location.pathname;
const { site } = useStaticQuery(
graphql`
query {
site {
siteMetadata {
title
description
}
}
}
`
)
const metaDescription = description || site.siteMetadata.description
return (
<Helmet
htmlAttributes={{
lang,
}}
title= "Hello"
titleTemplate={'%s | ${site.siteMetadata.title}'}
meta={[
{
name: 'description',
content: metaDescription,
},
{
property: 'og:title',
content: mylocation,
},
{
property: 'og:description',
content: metaDescription,
},
{
property: 'og:type',
content: 'website',
},
].concat(meta)}
>
<body className={mylocation} />
</Helmet>
)
}
SEO.defaultProps = {
lang: 'en',
meta: [],
description: '',
}
SEO.propTypes = {
description: PropTypes.string,
lang: PropTypes.string,
meta: PropTypes.arrayOf(PropTypes.object),
title: PropTypes.string.isRequired,
location: PropTypes.string,
}
export default SEO
渲染此页面时-> http://localhost:8000/about/ 我希望看到 mylocation = /about
我看到了
Error in function SEO in ./src/components/seo.js:14
Cannot read property 'pathname' of undefined
./src/components/seo.js:14
为什么我的位置属性未定义?
有没有更好的方法来为每个页面添加唯一的类或 ID?
【问题讨论】:
-
你是从父级传递历史对象吗?还是您正在浏览
<Link/>?如果您使用<Link/>,那么我相信您已经配置BrowserRouter来导航到SEO 组件?请澄清。
标签: reactjs location gatsby react-props react-helmet