如何在 Gatsby 中的页面之间传递数据?

dav*_*avl 3 gatsby

当我使用 Gatsby (V2) 路由到新页面时,我正在尝试传递数据

我希望然后能够检索该页面上的数据。这可能吗?我在没有运气的情况下对此进行了很多研究,所以我觉得好像我必须遗漏一些东西......谢谢

Chr*_*sis 6

如果你想传递道具,它可以像文档中的以下示例一样简单:

const PhotoFeedItem = ({ id }) => (
  <div>
    {/* (skip the feed item markup for brevity) */}
    <Link
      to={`/photos/${id}`}
      state={{ fromFeed: true }}
    >
      View Photo
    </Link>
  </div>
)

const Photo = ({ location, photoId }) => {
  if (location.state.fromFeed) {
    return <FromFeedPhoto id={photoId} />
  } else {
    return <Photo id={photoId} />
  }
}
Run Code Online (Sandbox Code Playgroud)

文档中的参考包括该行为的蛋头视频以澄清它。

https://www.gatsbyjs.org/docs/gatsby-link/#pass-state-as-props-to-the-linked-page

您还可以使用创建页面进行一些高级路由,并以编程方式生成页面。如果您的 gatsby 应用程序变得有点复杂,这会更高级一些但很有用。

https://www.gatsbyjs.org/docs/reach-router-and-gatsby/