gpt4 book ai didi

reactjs - 按日期订购 Contentful 中具有不同内容类型的帖子

转载 作者:行者123 更新时间:2023-12-04 12:23:19 25 4
gpt4 key购买 nike

这是我第一个使用 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
}
}
}
}
`)
然后我在另一个名为 的组件中编译所有组件。博客
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

最佳答案

而不是将每个内容类型包装在 WhateverSection 中组件,将所有三个内容数组组合成一个数组,对其进行排序,然后遍历组合数组,为每个条目呈现相关组件。
为了让这更合理,我将重构您对静态查询的使用,将它们提升到博客组件中,组合它们,并添加 GraphQL 别名以使检索数据不那么冗长。

const Blog = () => {
const data = useStaticQuery(graphql`
query {
images: allContentfulImage(sort: { fields: date, order: DESC }) {
nodes {
type: __typename
date
image {
description
file {
url
}
}
}
}

videos: allContentfulVideoEmbeds(sort: { fields: date, order: DESC }) {
nodes {
type: __typename
date
embedURL
}
}
}
`)

const dataForDisplay = [...data.images.nodes, ...data.videos.nodes].sort((a, b) => b.date - a.date)

return (
<div>
{dataForDisplay.map(({ type, ...props }) =>
React.createElement(componentTypeMap[type], props)
)}
</div>
)
}

export default Blog

const componentTypeMap = {
ContentfulImage: PhotoComponent,
ContentfulVideoEmbed: FilmComponent,
}

关于reactjs - 按日期订购 Contentful 中具有不同内容类型的帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64884226/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com