gpt4 book ai didi

javascript - 如何根据特定页面有条件地在 Gatsby 中呈现组件?

转载 作者:行者123 更新时间:2023-12-04 08:56:17 24 4
gpt4 key购买 nike

我正在 Gatsby 上构建一个网站,我希望能够根据我所在的页面有条件地呈现一个组件。例如,在页脚中我有一个组件,我不希望它出现在“我们的内容”页面上,但对于网站的其余部分是的。

我试过这样做,效果很好,但是在运行构建后给我一个错误提示:“窗口”在服务器端渲染期间不可用。

{ window.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

codesandbox显示了 @reach/routerlocation.pathname 实现。

关于javascript - 如何根据特定页面有条件地在 Gatsby 中呈现组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63818282/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com