我在 nextjs 工作,我正在尝试制作“动态路线”, 我想点击后我的网址应该像“myurl.com/article/55”
为此,我使用以下“链接标签”
<Link href={{pathname: "article/[id]",query: { id: post.id },}}>
<a className="rdmre-btn"> Read More</a>
</Link>
这是我在文件(“pages/article/[slug].js)”中的代码,我错在哪里?我希望每当我点击任何博客时,博客详细信息页面都应该打开。
import Axios from "axios";
import { useRouter } from "next/router";
import Link from "next/link";
import LatestBlogs from "../../components/LatestBlogs/LatestBlogs";
const Post = ({ post }) => {
const router = useRouter();
const htmlString = post.description_front;
if (router.isFallback) {
return <div>Loading...</div>;
}
return (
<>
<header className="bgbanner blog_header">
<div className="container cont">
<div className="header">
</div>
</div>
<div className="container "></div>
</header>
<section>
<div className="container Blog_page_sidebar">
<div className="blog_details">
<div className="blog_image">
<img src={post.image} />
</div>
<div className="blog_heading">
<h2>{post.title}</h2>
</div>
<div className="blog_detail">
<div
className="product-des"
dangerouslySetInnerHTML={{ __html: htmlString }}
/>
</div>
</div>
</div>
</section>
</>
);
};
export default Post;
export const getStaticProps = async ({ params }) => {
const { data } = await Axios.get(
`https://myurl.com/api/blogbyids/${params.id}`
);
const post = data;
return {
props: {
post,
},
};
};
export const getStaticPaths = async () => {
const { data } = await Axios.get(
"myurl.com/admin-panel/api/blogs"
);
const posts = data.slice(0, 10);
const paths = posts.map((post) => ({ params: { id: post.id.toString() } }));
return {
paths,
fallback: true,
};
};
[slug]
用于嵌套路由。但正确的是[...slug].js
(info)
示例:myurl.com/article/[id]/[otherid]
在上面的例子中我们可以看到 [id] 中可以嵌套子元素。您可以根据需要命名此参数。
如果你想要你的结构为
myurl.com/article/55
,你需要有如下结构:
在您的
pages
文件夹中:
article
(pages/article
)[id].js
(您可以命名为 [slug].js 或 [specialId].js - 无论名称如何这里是代码示例(URL:myurl.com/article/55;文件:pages/article/[pid].js)
import { useRouter } from 'next/router'
const Post = () => {
const router = useRouter()
//same name as name of your file, can be [slug].js; [specialId].js - any name you want
const { pid } = router.query
//result will be '55' (string)
return <p>Post: {pid}</p>
}
export default Post
在接下来的 14 中,您将需要使用 useParams,因为这将为您提供 URL 中的变量/slug。 https://nextjs.org/docs/app/building-your-application/routing/dynamic-routes
import { useParams } from "next/navigation";
const Post = () => {
// folder structure /posts/[pid]
const params = useParams();
// example URL /posts/123
const { pid } = params;
// pid will equal 123
return <p>Post: {pid}</p>
}
export default Post