我是新的nextjs,我需要使用一个API参数做一个动态URL我有一些类似于API
的数据[
{
"categories" : {
"department": "HR"
"location": "xxxx"
},
"id": "4d2f341-k4kj6h7g-juh5v3",
},
{
"categories" : {
"department": "Operarions"
"location": "xxxx"
},
"id": "4qd3452-fsd34-jfd3453",
},
{
"categories" : {
"department": "Marketing"
"location": "xxxx"
},
"id": "4d2f341-k4kwer37g-juh5v3",
},
]
我需要在index。js
中做类似的操作return(
<h1>More details</h1>
<a href="https://page.com/${id}"> link <a>
)
如果有人可以帮助我,请
是的,我会尽力帮助你的
假设你有一个名为records
的文件夹,那么你的url将是/records
在您提供的数据中,您有几个类别与ids
,您喜欢将其作为链接。(动态生成记录)
根据nextjs文档,您可以创建getStaticProps
页面并生成静态页面(这意味着它对SEO非常好,因此在SEO页面可见上使用它)
假设你有下面的结构:
/记录- (pid)。tsx(或js)
- index.tsx
这个结构意味着如果你去/records
URL你的索引文件将被触发。对于/records/4d2f341-k4kj6h7g-juh5v3
,您的[pid]文件将被触发。
在index.tsx
import Link from 'next/link'
const Records= ({ records }) => {
return(
<div className="container">
<h1>Records</h1>
{records.map(record=> (
<div>
<Link href={'/records/' + record.id} key={record.id}>
<a>
{record.categories.department}
</a>
</Link>
</div>
))}
</div>
);
}
export const getServerSideProps = async () => {
//your API path here
const res = await fetch('replace_by_your_api_route');
const data = await res.json()
return {
props: {records: data}
}
}
export default Records
in your [pid].tsx
import GeneralUtils from "lib/generalUtils";
const RecordDetails= ({record}) => {
return(
<div>
{record?
<div >
{record.categories.department} {record.categories.location}
</div>
: ''}
</div>
)
}
export async function getStaticProps(context) {
const pid = context.params.pid;
//your api path to get each record where pid it is your parameter you are passssing to your api.
const res = await fetch(process.env.APIpath + '/api/public/getRecord?pid=' + (pid));
const data = await res.json();
return {
props: {record: data}
}
}
export async function getStaticPaths() {
const res = await fetch('your_api_path_same_as_in_index_tsx')
const posts = await res.json()
// Get the paths we want to pre-render based on posts
const paths = posts.map((post) => ({
//your id of each record, for example 4d2f341-k4kj6h7g-juh5v3
params: { pid: post.id.toString() },
}))
// We'll pre-render only these paths at build time.
// { fallback: blocking } will server-render pages
// on-demand if the path doesn't exist.
return { paths, fallback: 'blocking' }
}
export default ProductDetails;
输出:-用户类型
/records
-他将有带有链接的记录列表
/records/4d2f341-k4kj6h7g-juh5v3
-他将有d2f341-k4kj6h7g-juh5v3的信息页面
仔细检查这个信息和这个视频