首页 > 解决方案 > 如何在 Gatsby 中的页面之间传递数据?

问题描述

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

我希望能够检索该页面上的数据。这可能吗?我已经对此进行了很多研究,但没有运气,所以我觉得好像我一定错过了什么……谢谢

标签: gatsby

解决方案


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

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} />
  }
}

文档中的参考包括一个关于行为的傻瓜视频以澄清它。

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/


推荐阅读