[英]Why am I getting undefined when attempting to loop over data in next js page (using getStaticProps)?
Having difficulty working with outputting the page meta data in next just when I run:在我运行时难以在下一个输出页面元数据:
npm run build
I get the following error:我收到以下错误:
Error occurred prerendering page "/blog/[...slug]". Read more: https://err.sh/next.js/prerender-error
TypeError: Cannot read property 'map' of undefined
This is the page I'm having an issue with:这是我遇到问题的页面:
//pages/blog/[...slug].js
import Head from 'next/head'
import Layout, { siteTitle } from '../../components/layout'
import axios from 'axios';
export default function About({ meta, title }) {
return (
<Layout home>
<Head>
<title>{title} | {siteTitle}</title>
{meta.map(meta_value => {
return (
<meta name={meta_value.name || meta_value.property} content={meta_value.content} />
);
})}
</Head>
</Layout>
)
}
export async function getStaticProps(context) {
const res = await axios.get(`https://example.com/api/posts?url=/${context.params.slug.join('/')}`);
const post = await res.data;
return {
props: {
title: post.title,
meta: post.meta
},
}
}
export async function getStaticPaths() {
const res = await axios.get('https://example.com/api/posts?categories=3');
const posts = await res.data;
const slugs = posts.map(post => post.permalink.replace(/^\/|\/$/g, '').split("/") );
const paths = slugs.map(slug => ({params: { slug } } ));
return {
paths,
fallback: true,
}
}
Sample response from api:来自 api 的示例响应:
{
"title" : "test",
"meta": [
{
"property": "og:locale",
"content": "en_GB"
},
{
"property": "og:type",
"content": "article"
},
{
"property": "og:title",
"content": "Test Post"
},
{
"property": "og:description",
"content": "testing"
},
{
"property": "og:url",
"content": "https://example.com/blog/2021/01/test/"
},
{
"property": "og:site_name",
"content": "Test Site"
},
{
"property": "article:published_time",
"content": "2021-01-30T13:32:26+00:00"
},
{
"property": "article:modified_time",
"content": "2021-01-30T13:58:00+00:00"
},
{
"name": "twitter:card",
"content": "summary_large_image"
},
{
"name": "twitter:label1",
"content": "Estimated reading time"
},
{
"name": "twitter:data1",
"content": "1 minute"
}
]
}
"getStaticProps" only runs at build time, which means that the context parameter won't contain "params" which comes from the url. “getStaticProps”仅在构建时运行,这意味着上下文参数不会包含来自 url 的“params”。 Which i'm guessing will result in an response with undefined data.
我猜这将导致未定义数据的响应。
Try to replace GetStaticProps with getServerSideProps , which prerenders the page with new data on each request instead of at build time.尝试将 GetStaticProps 替换为getServerSideProps ,它会在每个请求而不是在构建时使用新数据预呈现页面。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.