【发布时间】:2021-07-12 13:51:04
【问题描述】:
首先我将展示我拥有的代码,然后解释问题:
我的 gatsby-node.js 上有这个:
const path = require(`path`)
const { createFilePath } = require(`gatsby-source-filesystem`)
exports.onCreateNode = ({ node, getNode, actions }) => {
const { createNodeField } = actions
if (node.internal.type === `ContetnfulPost`) {
const slug = createFilePath({ node, getNode, basePath: `pages` })
createNodeField({
node,
name: `slug`,
value: slug,
})
}
}
exports.createPages = async ({ graphql, actions }) => {
const { createPage } = actions
const result = await graphql(`
query {
allContentfulPost {
edges {
node {
postTitle
slug
}
}
}
}
`)
const posts = result.data.allContentfulPost.edges
posts.forEach(({ node }, index) => {
createPage({
path: `${node.slug}`,
component: path.resolve(`./src/templates/blogPost.js`),
context: {
slug: node.slug,
prev: index === 0 ? null : posts[index - 1].node,
next: index === posts.length - 1 ? null : posts[index + 1].node,
},
})
})
}
然后我在 2 个地方查询博客文章:一个像这样的博客页面:
blog.js页面:
function Blog() {
return (
<Layout>
<SEO title="Blog Page" />
<StaticQuery
query={graphql`
query blogQuery {
allContentfulPost {
edges {
node {
slug
postTitle
postImage {
file {
url
fileName
}
}
postContent {
postContent
}
postDate
}
}
}
}
`}
render={data => (
<ul>
{data.allContentfulPost.edges.map(({ node }) => {
return (
<BlogPostsContainer>
<Link to={`${node.slug}`}>
<BlogPostImage src={node.postImage.file.url} />
<PostTitle>{node.postTitle}</PostTitle>
</Link>
</BlogPostsContainer>
)
})}
</ul>
)}
/>
</Layout>
)
}
另一个是我用来在主页上显示我的一些帖子的反应组件:
BlogSection.js
function BlogSection() {
return (
<BlogSectionWrapper>
<StaticQuery
query={graphql`
query homeBlogQuery {
allContentfulPost(limit: 2) {
edges {
node {
slug
postTitle
postImage {
file {
url
fileName
}
}
postContent {
postContent
}
postDate
}
}
}
}
`}
render={data => (
<ul>
{data.allContentfulPost.edges.map(({ node }) => {
return (
<HomePostsContainer>
<Link to={`${node.slug}`}>
<HomePostImage src={node.postImage.file.url} />
<PostTitle>{node.postTitle}</PostTitle>
</Link>
</HomePostsContainer>
)
})}
</ul>
)}
/>
<ButtonWrapper></ButtonWrapper>
<FlatButton
item={{
title: "See all posts",
icon: "/images/icons/book.svg",
link: "/blog",
}}
/>
</BlogSectionWrapper>
)
}
现在的问题是,当我从主页(从BlogSection.js 组件呈现的)点击博客文章时,URL 通常是http://localhost:8000/test-post。
但是当我从博客页面(从blog.js 文件呈现)中单击帖子时,URL 变为http://localhost:8000/blog/test-post。
我还在每个帖子上添加了 Prev 和 Next 按钮,当我点击它们时,它只是在 URL 中附加了 slug,例如当我在 http://localhost:8000/test-post 并点击 Next 时,它变为http://localhost:8000/test-post/test-post2。
如何保留 URL 以仅显示帖子 slug 或者可能为所有帖子添加 /blog 前缀,而与我点击它的位置无关?
我在gatsby-node.js 文件上试过这个,但它不起作用:
posts.forEach(({ node }, index) => {
createPage({
path: `/blog/${node.slug}`, //<===== THIS LINE
component: path.resolve(`./src/templates/blogPost.js`),
context: {
slug: node.slug,
prev: index === 0 ? null : posts[index - 1].node,
next: index === posts.length - 1 ? null : posts[index + 1].node,
},
})
})
【问题讨论】:
标签: javascript reactjs graphql gatsby contentful