Javascript 如何在<;中动态设置标题;头>;通过getStaticProps()在Next.js上
我正在为我的Next.js应用程序上的特定帖子预呈现此页面:Javascript 如何在<;中动态设置标题;头>;通过getStaticProps()在Next.js上,javascript,reactjs,next.js,server-side-rendering,getstaticprops,Javascript,Reactjs,Next.js,Server Side Rendering,Getstaticprops,我正在为我的Next.js应用程序上的特定帖子预呈现此页面: import Head from 'next/head'; import Link from 'next/link'; import client from '../../lib/apollo/client' import POSTS_WITH_SLUGS from '../../lib/queries/allposts' import POST from '../../lib/queries/post' import styles
import Head from 'next/head';
import Link from 'next/link';
import client from '../../lib/apollo/client'
import POSTS_WITH_SLUGS from '../../lib/queries/allposts'
import POST from '../../lib/queries/post'
import styles from '../../styles/Home.module.css';
import blogStyles from '../../styles/Blog.module.css';
export default function Post({ postData }) {
const router = useRouter();
if (!router.isFallback && !postData?.slug) {
return <p>hmm... looks like an error</p>
}
const formatDate = date => {
const newDate = new Date(date);
return `${newDate.getDate()}/${
newDate.getMonth() + 1
}/${newDate.getFullYear()}`
};
return (
<div className={styles.container}>
<Head>
<title>{postData.title}</title>
<link rel='icon' href='/favicon.ico' />
</Head>
<main className={styles.main}>
{router.isFallback ? (
<h2>Loading...</h2>
) : (
<article className={blogStyles.article}>
<div className={blogStyles.postmeta}>
<h1 className={styles.title}>{postData.title}</h1>
<p>{formatDate(postData.date)}</p>
<img src={postData.featuredImage.node.sourceUrl} />
</div>
<div
className='post-content content'
dangerouslySetInnerHTML={{ __html: postData.content }}
/>
</article>
)}
<p>
<Link href={`/blog`}>
<a>Back</a>
</Link>
</p>
</main>
</div>
)
}
export async function getStaticPaths() {
// const allPosts = await getAllPostsWithSlug();
const { data } = await client.query({
query: POSTS_WITH_SLUGS
});
if (
data?.posts &&
data?.posts.edges !== null &&
data?.posts.edges.node !== null &&
data?.posts.edges.length > 0
) {
return {
paths: data?.posts.edges.map(({ node }) => `/blog/${node.slug}`) || [],
fallback: true
}
}
}
export async function getStaticProps({ params }) {
const { data } = await client.query({
query: POST,
variables: {
id: params.slug,
idType: 'SLUG'
}
});
return {
props: {
postData: data.post
}
};
}
我相信这个错误是由于
组件引起的,下一步我试图通过{postData.title}
动态设置
。我从getStaticProps()
获取数据作为道具
我不确定我犯了什么错误,但我确实想知道是否必须在
/pages
目录外创建
组件。任何帮助都将不胜感激。谢谢 让我解释一下,在初始构建后请求任何其他帖子时,Next.js将如何“回退”。有两个选项可供选择:blocking
和true
(首选)–当对尚未生成的页面发出请求时,Next.js将在第一次请求时呈现该页面。将来的请求将为缓存中的静态文件提供服务fallback:blocking
–当对尚未生成的页面发出请求时,Next.js将立即为静态页面提供服务,并在第一次请求时显示加载状态。数据加载完成后,页面将使用新数据重新呈现并缓存。将来的请求将为缓存中的静态文件提供服务fallback:true
除非您希望提供静态加载shell,然后在客户端加载您的帖子,否则我将从
true
更改为blocking
。那会解决你的问题 这和你的问题不一样吗?请不要为同一问题创建多个问题。
Error occurred prerendering page "/blog/[slug]". Read more: https://err.sh/next.js/prerender-error
TypeError: Cannot read property 'title' of undefined