我想映射Gatsby模板中的frontmatter子项。信息框有子项,我想映射信息框,因为它们会随着文章的变化而变化。有些文章可能有3个,其他文章可能有10个。有些文章会有日期和全名,其他文章会有不同的名字,例如地址、出生日期等
代替
{
infoboxItems.map((item, index) => {
<li key={index}>
{item.fullName}
{item.date}
{item.this}
{item.something_here}
</li>
})
}
我希望信息框在不指定全名、日期、this和something_here的情况下返回项目
应该返回任何Mdx文件
differentSubItem: anything
AnotherSubItem: anything
thisSubItem: that
Mdx文件1
---
title: this is is the title
description: this is sthe description of the article here.
featuredImage: ../../src/images/myimage.png
infobox:
- date: somedate
- something_here: nothing
- this: that
---
#This is a test article
Hi this is a test article
##this is a title
this is some text
###this is h3
this is some text
Mdx文件2
---
title: another title comes
description: this a SEO Description for title 2
featuredImage: ../../src/images/myimage2.png
infobox:
- dateOfBirth: somedate
- addressOfPublisher: 123 Main Street
- phoneNumber: 000 000 0000
---
#This is a test article
Hi this is a test article
##this is a title
this is some text
###this is h3
this is some text
模板文件{mdx.slug}.jsx
import React from "react"
import { graphql } from "gatsby"
import { GatsbyImage, getImage } from "gatsby-plugin-image"
import { MDXRenderer } from 'gatsby-plugin-mdx'
const EnglishArticleTemplate = ({ data }) => {
// console.log("all data")
// console.log(data)
const article = data.mdx //all articles
// console.log("article")
// console.log(article)
const featuredImage = getImage(article.frontmatter.featuredImage)
const infoboxItems = article.frontmatter.infobox
// console.log("infobox items")
// console.log(infoboxItems)
return (
<div>
<h1>{article.frontmatter.title}</h1>
<GatsbyImage image={featuredImage} />
<MDXRenderer>
{article.body}
</MDXRenderer>
{
infoboxItems.map((item, index) => {
// <li key={index}>
// {item.fullName}
// </li>
})
}
</div>
)
}
export const query = graphql`
query GetPostById ($id: String) {
mdx (id: {eq: $id}) {
frontmatter {
featuredImage {
childImageSharp {
gatsbyImageData(
transformOptions: {cropFocus: CENTER}
placeholder: BLURRED
formats: WEBP
blurredOptions: {width: 100}
)
}
}
title
infobox {
date
fullName
something_here
this
dateOfBirth
addressOfPublisher
phoneNumber
}
}
id
body
slug
}
}
`
export default EnglishArticleTemplate
首先,您的map
循环不会工作,因为您没有返回任何内容。更改为:
{
infoboxItems.map((item, index) => {
return <li key={index}>{item.fullName}</li>;
});
}
关于你的问题,你可以简单地使用Object.keys
或Object.values
方法从一个对象(infobox
(中获得一个键/值数组来循环,而无需事先知道它们,因此无需专门访问每个位置:
Object.keys(article.frontmatter.infobox).forEach((key, index)) => {
console.log(`${key}: ${article.frontmatter.infobox[key]}`);
}
应用于您的JSX,类似于:
{
Object.keys(article.frontmatter.infobox).map((key) => {
return <li key={key}>{article.frontmatter.infobox[key]}</li>;
});
}
注意forEach
而不是map
循环的变化。