无法读取未定义的属性(读取“当前”)我无法从数组中获取slug

问题描述 投票:0回答:1

当前页面未显示

我无法从数组中获取当前的slug

堆栈: 后端:理智 前端:Astro.build

理智

import { defineField, defineType } from 'sanity' export default defineType({ name: 'art', title: 'Arts', type: 'document', fields: [ defineField({ name: 'year', title: 'Year', type: 'string', options: { hotspot: true, }, }), defineField({ name: 'images', title: 'Arts', type: 'array', of: [{ name: 'object', title: 'object', type: 'object', options: { hotspot: true, }, fields: [{ name: 'image', type: 'image', title: 'image', }, { name: 'title', type: 'string', title: 'Title', }, { name: 'slug', title: 'Slug', type: 'slug', options: { source: 'title', maxLength: 96, }, }, ], }, ], }), ] })
天文
[鼻涕虫].astro

--- import Layout from '../../layouts/Page.astro' import { useSanityClient } from "astro-sanity"; export async function getAllArts() { const query = `*[_type == 'art']`; const data = await useSanityClient().fetch(query); return data; } export interface Props { art: any; } export async function getStaticPaths() { const allArtInfo = await getAllArts(); return allArtInfo.map(art => ({params: { slug: art.images.slug.current }, props: {art}})); } const { art } = Astro.props; const seo = { title: '', description: '', } --- <Layout seo={seo}> <!-- <h1>{art.title}</h1> --> </Layout>
尝试从“images”数组中显示当前页面

当我没有写输出时: 无法读取未定义的属性(读取“当前”)

如果在“图片”前添加[0]

return allArtInfo.map(art => ({params: { slug: art.images[0].slug.current }, props: {art}}));
页面显示当前的 slug。仅第一个数组。如何让一切顺利?

javascript arrays slug sanity astrojs
1个回答
0
投票
因此,您有一个艺术数组,每个艺术数组都有一个图像数组,因此您有一个图像数组的数组,您需要在单个数组中展开这些图像,同时保留对需要传递的每个图像中的艺术的引用道具。

您需要一个双循环,首先循环遍历所有艺术作品,然后第二次循环遍历图像。然后你用第二个循环图像和循环艺术推送一个新结构,就像这样

export async function getStaticPaths() { const allArtInfo = await getAllArts(); const allArtImages = [] allArtInfo.forEach(art => { art.images.forEach((image)=>{ allArtImages.push({image:image,art:art}) }) }); return allArtImages.map(image => ({params: { slug: image.slug.current }, props: {image.art}})); }
    
© www.soinside.com 2019 - 2024. All rights reserved.