在Next.js的[slug].js中获取同分类其他博客数据的方法
实现同一分类博客侧边栏展示
你可以通过以下步骤实现同一分类下其他博客的侧边栏展示:
步骤1:修改getStaticProps获取同分类博客
在getStaticProps中,先获取当前详情页的博客数据,再利用该博客的cat_name请求同分类的其他博客,同时排除当前博客本身:
export const getStaticProps = async ({ params }) => { // 获取当前博客详情 const { data: post } = await Axios.get(`xxxxxxxxxxxxxxxxxxxxxxxxx/${params.slug}`); // 根据分类名称请求同分类博客 const { data: relatedPosts } = await Axios.get(`http://xxxxxxxxxxx.com/xxxxxxxxxxxxxxxx/blogs?cat_name=${encodeURIComponent(post.cat_name)}`); // 过滤掉当前博客,避免在侧边栏显示自己 const filteredRelatedPosts = relatedPosts.filter(item => item.slug !== params.slug); return { props: { post, relatedPosts: filteredRelatedPosts }, }; };
注意:请确保你的后端API支持通过
cat_name参数筛选博客,若API参数名不同,需对应调整请求地址。
步骤2:在组件中接收并渲染同分类博客
修改Post组件,接收relatedPosts props,然后在右侧侧边栏动态渲染这些博客:
import Axios from "axios"; import { useRouter } from "next/router"; import Link from 'next/link' const Post = ({ post, relatedPosts }) => { const router = useRouter(); if (router.isFallback) { return <div>Loading...</div>; } return ( <> <header className="inner-header"> <div className="container"> <nav className='navbar navbar-expand-lg main-header' > <Link href="/"> <a className="navbar-brand" href=''> <img src="/img/logo1.png" /> </a> </Link> <button className="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarCollapse"> <span className="navbar-toggler-icon"><img src="/img/list.svg" /></span> </button> </nav> </div> </header> <div className="alfa-img"> <div className="container"> <div className="row"> <div className="col-md-7"> <div className="release-time"> <img className="mask-img" src={post.image} /> </div> <div className="game-re"> <h2>{post.title} !</h2> {post.description} </div> </div> <div className="col-md-5"> <div className="pined"> <h3>同分类博客</h3> {/* 动态渲染同分类博客列表 */} {relatedPosts.length > 0 ? ( relatedPosts.map(relatedPost => ( <div key={relatedPost.slug} className="img-content"> <div className="img-pined"> <img className="mask-on" src={relatedPost.image || "/img/Mask Group 11.png"} /> </div> <div className="alfa-lp"> <h4> <Link href={`/posts/${relatedPost.slug}`}> <a>{relatedPost.title}</a> </Link> </h4> <p>{relatedPost.description?.substring(0, 150)}...</p> <h6 className="post-date post">Posted: {relatedPost.post_date || "Unknown date"}</h6> </div> </div> )) ) : ( <p>暂无同分类博客</p> )} </div> </div> </div> </div> </div> </> ); }; export default Post; // getStaticPaths 部分保持不变 export const getStaticPaths = async () => { const { data } = await Axios.get("http://xxxxxxxxxxx.com/xxxxxxxxxxxxxxxx/blogs"); const posts = data.slice(0, 10); const paths = posts.map((post) => ({ params: { slug: post.slug.toString() } })); return { paths, fallback: true, }; };
补充说明
- 确认
post对象包含cat_name字段,若字段名不同(如category),需对应修改代码中的字段引用。 - 图片部分增加了默认图兜底,若相关博客无
image字段,会显示默认图,可根据实际需求调整路径。 - 描述内容截取前150字符,避免侧边栏内容过长,可按需调整截取长度。
内容的提问来源于stack exchange,提问作者amit
相关产品推荐
相关产品推荐

