[英]Getting value of property of object inside an array inside another array
我正在使用 Strapi 和 React 開發一個博客,並且博客中的文章有多個類別,我從 Strapi 得到一個 GraphQL 查詢,如下所示
(blogpostObject){
"categories": [
{
"name": "Category 1"
},
{
"name": "Category 2"
},
],
}
我想訪問每個類別的“名稱”值,並用逗號分隔它們,每個類別都帶有一個<a>
標記,並帶有指向另一個頁面的鏈接。
到目前為止,我只提出了這個解決方案
queryData.map(article => (
article.categories.map(category => category.name).toString().replace(/,/g, `, `)
這將呈現:“類別 1,類別 2”,但我不知道如何從此處將<a>
標記添加到每個標記。
編輯:我使用 Gatsby 來構建這個項目,所以我使用 React Link 組件來處理內部鏈接。
這是一個示例 GraphQL 響應
{
"data": {
"allStrapiArticle": {
"nodes": [
{
"title": "This is my second article",
"slug": "this-is-my-second-article",
"content": " Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
"id": "Article_2",
"author": {
"name": "Average Joe"
},
"categories": [
{
"name": "Category 1"
}
],
"created_at": "Wednesday, June 24th 2020"
}
import React from "react";
// this data would come from graphql instead
const data = {
allStrapiArticle: {
nodes: [
{
title: "This is my second article",
slug: "this-is-my-second-article",
content: " Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
id: "Article_2",
author: {
name: "Average Joe"
},
categories: [
{
name: "Category 1"
},
{
name: "Category 2"
},
{
name: "Category 3"
}
],
created_at: "Wednesday, June 24th 2020"
}
]
}
};
const App = () => {
return (
<div>
{data.allStrapiArticle.nodes.map(node => {
return node.categories.map((category, index) => {
return (
<>
<a href="/">{category.name}</a>
{index < node.categories.length - 1 && ", "}
</>
);
});
})}
</div>
);
};
export default App;
你試過了嗎
article.categories.map(category => <a href='#'>{category.name}</a>)
queryData.map(article => (
article.categories.map(category => "<a href='#'>" + category.name + "</a>").toString().replace(/,/g, `, `
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.