簡體   English   中英

如何根據特定頁面有條件地呈現 Gatsby 中的組件?

[英]How do I conditionally render a component in Gatsby based on specific page?

我正在 Gatsby 上建立一個網站,我希望能夠根據我所在的頁面有條件地呈現一個組件。 例如,在頁腳中我有一個組件,我不希望它出現在“我們的內容”頁面上,但對於網站的其余部分是。

我嘗試這樣做,這奏效了,但是在運行構建后給我一個錯誤提示: "window" is not available during server side rendering.

{ window.location.pathname !== '/ourcontent'
  ? <MyComponent />
  : null
}

我使用功能組件工作。

我將如何能夠實現這一目標? 任何幫助將不勝感激! 非常感謝您的先進!

在任何 Gatsby 頁面組件上,您都應該有一個location屬性。 然后你可以使用props.location.pathname獲取路徑名。 很確定這也適用於服務器端渲染(您的構建)。

實現它的最簡單和最簡單(最干凈)的方法是使用 Gatsby 提供的內置props 正如您在他們的文檔中所見,它公開了一個location prop ,其中包含所有需要的信息。 當然,因為它不是一個全局的瀏覽器對象,比如windowdocument ,它在服務器端渲染期間以及運行時期間都是可用的。

您可以簡單地:

import React from "react"
import { graphql } from "gatsby"

const Component = ({ location, data }) => {
  return location.pathname !== 'ourcontent' ? <MyComponent /> : null
}
export default Component

您可以通過使用location.pathname !== 'ourcontent' && <MyComponent />刪除三元條件來改進它,不需要返回null

您也可以使用@reach/router 這是一個非常簡單的例子。

import { Location } from '@reach/router'


const IndexPage = () => (
  <Layout>
    <h1>Hi people</h1>
    <Location>
      {({ location }) => {
        console.log(location)
        if (location === '/') return <p>You are on the homepage {location.pathname}</p>
        return <h1> you are not on the homepage </h1>
      }}
    </Location>
  </Layout>
)

export default IndexPage

代碼和框顯示了@reach/routerlocation.pathname

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM