How to get pathname in the layout file in gatsby

∥☆過路亽.° 提交于 2019-12-11 12:44:15

问题


I am working with gasby and here the main file is always layout.js which is the parent of them all. Since it is a parent file then how can I get a location props this.props.location.pathname inside it?

Here is my layout component

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.

回答1:


As stated in the Gatsby docs:

In v1, the layout component had access to history, location, and match props. In v2, only pages have access to these props; if you need these props in the layout component, pass them through from the page.

What this is means is that you need to go to where your Layout component is rendered, which will be the index.js or app.js page usually, and pass the the location props to it directly:

import React from "react"
import Layout from "../components/layout"

export default props => (
  <Layout location={props.location}>
    <div>Hello World</div>
  </Layout>
)

Then you can use it in your layout. You can also read more here.



来源:https://stackoverflow.com/questions/55631403/how-to-get-pathname-in-the-layout-file-in-gatsby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!