我有一些警報組件。從我想傳遞的每個組件中傳遞 itm._id
并在 [itm].jsx 的同一檔案夾中的 [itm].jsx 中接收它我想在 getServerSideProps 函式中使用它來獲取資料
索引.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 Object] reason: Unexpected token < in JSON at position 0
我認為錯誤是 id 被接收為物件我該如何解決這個問題
[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,
},
};
}



uj5u.com熱心網友回復:
試試這個:在鏈接標簽通過查詢作為
<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
}
uj5u.com熱心網友回復:
您必須從如下查詢中接收它。查詢自己一個物件。在物件內部,您的路徑變數作為您的動態檔案名存在。您正在按物件獲取資料。您必須通過它的別名獲取資料id1。
export async function getServerSideProps({ query }) {
var {itm: id1} = query;
...
return {
props: {
posts,
answerPosts,
},
};
}
uj5u.com熱心網友回復:
如果您查看檔案,getServerSideProps您會看到引數被呼叫context- 這是一個物件,而不是您期望的 id。
https://nextjs.org/docs/api-reference/data-fetching/get-server-side-props
export async function getServerSideProps(context) {
return {
props: {}, // will be passed to the page component as props
}
}
參考:
context 引數是一個包含以下鍵的物件:
- req:HTTP IncomingMessage 物件。
- res:HTTP 回應物件。
- 查詢:表示查詢字串的物件。
(其他已洗掉)
因此,您的查詢引數將位于context.query.
試試這個:
export async function getServerSideProps(context) {
const query = context.query
console.log(query?.itm);
// ^
}
您命名了查詢引數itm(因為檔案稱為 [itm].tsx) - 因此 context.query.itm 應該為您提供所需的值。在添加 URL 之前檢查控制臺。
uj5u.com熱心網友回復:
我認為問題在于您沒有從 getServerSideProps 的引數中解構查詢錯誤告訴您您正在向 /[object object] 發出請求,這意味著您的 id 不是字串它是 getServerSideProps 函式的整個 props 物件.
匯出異步函式 getServerSideProps(query)
將其替換為
匯出異步函式 getServerSideProps({query})
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/480943.html
標籤:javascript 反应 下一个.js
