盖茨比链接通过道具将上一页的位置.路径传递到下一页



我有几个生成的页面,其中分页列出了我的所有博客文章,每个博客文章都是使用createPage()从markdown生成的。每个生成的/posts页面包含3个帖子的预览和以下页面获得一个数字添加posts/2…等

我想把我当前索引页的路径(例如可以是/posts/3)传递给我点击的Blog页面,所以我可以设置一个"返回"。每个链接。我可以使用Link组件中的state属性传递数据,但我不确定传递位置。从带有props的列表页面的路径是正确的方式,因为它不起作用,它链接到实际的当前页面。

为了可读性我省略了import语句和不相关的代码。

gatsby-node.js

const { createPage } = actions
const blogPostTemplate = require.resolve(path.join(__dirname, `src`, `templates`, `blog-post-template.js`))
const blogListTemplate = require.resolve(path.join(__dirname, `src`, `templates`, `blog-list-template.js`))
const blogPosts = result.data.allMarkdownRemark.edges
// Create the list pages of the blog posts using the Awesome Pagination plugin
paginate({
createPage, 
items: blogPosts,
itemsPerPage: 3,
pathPrefix: `/posts`,
component: blogListTemplate
})

// Create a page for each blog post
blogPosts.forEach(({ node }) => {
createPage({
path: node.frontmatter.slug,
component: blogPostTemplate,
context: {
slug: node.frontmatter.slug,
}
})
})

blog-list-template

const BlogListTemplate = ({ data, pageContext, location }) => {
const pathBack= location.pathname
return (
<Layout>
{posts.map(({ node }) => (
<Preview
key={node.id}
to={node.frontmatter.slug}
from={pathBack}
title={node.frontmatter.title}
date={node.frontmatter.date}
excerpt={node.excerpt}
/>
))}
</Layout>
) 
}

preview.js

const Preview = ({ to, from, title, date, excerpt}) => {
console.log("This is preview: path ", from)
return(
<div>
<Link
to={to}
state={{ path: from}}
>
<h2>{title}</h2>
<p> - {date} - </p>
</Link>
<p>{excerpt}</p>
</div>
)
}

blog-post-template.js

const BlogPostTemplate = ({ data, path }) => {
return (
<Layout>
<div className="blogPost">
<Link to={path}>Tillbaka</Link>
<h1>{frontmatter.title}</h1>
<div className="blog-post-content" dangerouslySetInnerHTML={{__html: html}} />
<p>Publicerad: {frontmatter.date}</p>
</div>
</Layout>

您的方法是完全有效的(在我看来是最简单和最干净的)。您错过了props解构以获得path。您的代码应该看起来像:

const BlogPostTemplate = ({ data, location }) => {
return (
<Layout>
<div className="blogPost">
<Link to={location.state.path}>Tillbaka</Link>
<h1>{frontmatter.title}</h1>
<div className="blog-post-content" dangerouslySetInnerHTML={{__html: html}} />
<p>Publicerad: {frontmatter.date}</p>
</div>
</Layout>

我不知道是不是打错了,但是frontmatter会变成undefined,在这段代码中破坏你的代码,我猜你是想做data.frontmatter

请注意,通过<Link>状态发送的所有内容都需要作为props.location.state进行检索,正如您在文档的示例中看到的那样:

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

最新更新