【发布时间】:2021-03-01 04:46:00
【问题描述】:
这是我第一个使用 GatsbyJS 和 Contentful 的项目。现在我在网站上有几篇不同内容模型的帖子。为了简单起见,假设我有一些内容类型是照片,而其他内容类型是视频嵌入。我正在使用 GraphQL 来获取帖子...
每种类型都有不同的组件。
照片(也称为 PhotoSection)
const data = useStaticQuery(graphql`
query {
allContentfulImage(sort: { fields: date, order: DESC }) {
edges {
node {
image {
description
file {
url
}
}
}
}
}
}
`)
视频嵌入(也称为电影部分)
const data = useStaticQuery(graphql`
query {
allContentfulVideoEmbeds(sort: { fields: date, order: DESC }) {
edges {
node {
embedURL
}
}
}
}
`)
然后我在另一个名为 Blog
的组件中编译所有组件const Blog = () => {
return (
<div>
<AudioSection />
<FilmSection />
<PhotoSection />
</div>
)
}
export default Blog
最终结果是帖子按日期降序排列,但它们也按其部分/内容类型组织。如果您遵循代码块,则顺序是 AudioSection -> FilmSection -> PhotoSection。无论内容类型如何,我都希望它们按日期(最新的优先)排序。
希望这是有道理的。不太确定在这里做什么?
提前谢谢你
编辑... 这是尝试建议的帖子。我剪掉了一些较大的部分,但留下了 PhotoComponent 作为示例
const BlogTwo = () => {
const data = useStaticQuery(graphql`
query {
music: { bla bla bla }
videos: { bla bla bla }
images: allContentfulImage(sort: { fields: date, order: DESC }) {
nodes {
type: __typename
image {
description
file {
url
}
}
}
}
`)
const dataForDisplay = [data.music, data.images, data.videos].sort(
(a, b) => b.date - a.date
)
const componentTypeMap = {
ContentfulMusicAndArt: MusicComponent,
ContentfulImage: PhotoComponent,
ContentfulVideoEmbeds: FilmComponent,
}
const MusicComponent = () => {
return (
<div>
bla bla bla
</div>
)
}
const PhotoComponent = () => {
return (
<div className={`${blogStyles.blogDiv}`}>
<div className={`${blogStyles.blogPost} ${blogStyles.image}`}>
<img
src={data.images.nodes.image.file.url}
alt={data.images.nodes.image.description}
/>
</div>
</div>
)
}
const FilmComponent = () => {
return (
<div>
bla bla bla
</div>
)
}
return (
<div>
{dataForDisplay.map(({ type, props }) =>
React.createElement(componentTypeMap[type], props)
)}
</div>
)
}
export default BlogTwo
【问题讨论】:
标签: reactjs graphql gatsby contentful static-site