gpt4 book ai didi

javascript - 将 id 通过 Link 传递给 getServerSideProps :next js

转载 作者:行者123 更新时间:2023-12-05 01:04:18 25 4
gpt4 key购买 nike

我有一些警报组件。从我想传递 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,
},
};
}

enter image description here

enter image description here

enter image description here

最佳答案

试试这个:在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com