我有一些警报组件。从我想传递 itm._id 的每个组件中
并在 [itm].jsx 的同一文件夹中的 [itm].jsx 中接收它,我想在 getServerSideProps 函数中使用它来获取数据
index.jsx
<div className="question11">
{data.map((itm) => (
<Link
key={itm._id}
href={{
pathname: "/[itm]",
query: itm._id,
}}
as={`/${encodeURIComponent(
itm.Name.replace(/[^a-zA-Z0-9 - _ . ~]/g, "").replace(
/ /g,
"-"
)
)}`}
>
<Alert className="question13">{itm.Name}</Alert>
</Link>
))}
</div>
流动是 getServerSideProps 函数,我现在得到的错误是
Server Error FetchError: invalid json response body at https://askover.wixten.com/questone/[object%20Object] reason: Unexpected token < in JSON at position 0
我认为错误是 id is recided as object 我该如何解决这个问题
[itm].jsx
export async function getServerSideProps(query) {
var id1 = query;
console.log(id1);
const queryRequest = fetch("https://askover.wixten.com/questone/" + id1).then(
async (res) => await res.json()
);
const answerRequest = fetch(
"https://askover.wixten.com/answersapi/" + id1
).then(async (res) => await res.json());
const responses = await Promise.all([queryRequest, answerRequest]);
const [posts, answerPosts] = await Promise.all(responses);
return {
props: {
posts,
answerPosts,
},
};
}
最佳答案
试试这个: 在 Link Tag 中传递查询为
<div className="question11">
{data.map((itm) => (
<Link
key={itm._id}
href={{
pathname: "/[itm]",
query: {id: itm._id},
}}
as={`/${encodeURIComponent(
itm.Name.replace(/[^a-zA-Z0-9 - _ . ~]/g, "").replace(
/ /g,
"-"
)
)}`}
>
<Alert className="question13">{itm.Name}</Alert>
</Link>
))}
</div>
在 getserversideprops 中你可以像这样访问它
export async function getServerSideProps(context) {
console.log(contex.params.id) //If doesn't work use context.query.id
}
关于javascript - 将 id 通过 Link 传递给 getServerSideProps :next js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72360423/