javascript - 如何在 gatsby 的布局文件中获取路径名
问题描述
我正在使用gasby
,这里的主文件始终layout.js
是它们的父文件。既然它是一个父文件,那么我怎样才能this.props.location.pathname
在其中获取位置道具?
这是我的布局组件
class Layout extends Component {
componentWillMount() {
console.log(this.props, 'dssssssssssssf')
}
render() {
const { children } = this.props
return(
<StaticQuery
query={graphql`
query SiteTitleQuery {
site {
siteMetadata {
title
}
}
}
`}
render={data => (
<>
<div>
<Provider store={store}>
{children}
</Provider>
</div>
</>
)}
/>
)
}
}
Layout.propTypes = {
children: PropTypes.node.isRequired
}
export default Layout.
解决方案
正如盖茨比文档中所述:
在 v1 中,布局组件可以访问历史记录、位置和匹配道具。在 v2 中,只有页面可以访问这些道具;如果您在布局组件中需要这些道具,请从页面中传递它们。
这意味着您需要转到 Layout 组件的渲染位置,通常是 index.js 或 app.js 页面,并将 location 属性直接传递给它:
import React from "react"
import Layout from "../components/layout"
export default props => (
<Layout location={props.location}>
<div>Hello World</div>
</Layout>
)
然后你可以在你的布局中使用它。您还可以在此处阅读更多内容。
推荐阅读
- mysql - AWS:“无效的身份池配置。检查为该池分配的 IAM 角色。” AWS Lambda 查询 MYSQL 数据库时出错
- java - “spring-boot-starter-integration”依赖的目的是什么?
- python - 在pytorch中将矩阵行乘以向量元素?
- php - 执行 Composer 命令时出现错误“'php' 未被识别为内部或外部命令、可运行程序或批处理文件”
- python - 将 python 列表作为列写入谷歌表
- swift - 这是什么 NSDate 格式?
- git - 从上游开发分支更新分叉回购?(不是我们可以合并的东西)
- javascript - 选择类别并将其推送到数据库后出现问题,它显示未定义
- javascript - 如何避免在制作之前选择输入元素?
- android - androidx 迁移后,Android Studio 应用程序未安装在模拟器上