[英]How to pass a parameter in getStaticProps in Nextjs
我只想問當用戶“單擊搜索按鈕”並在 NextJS 中顯示適當的結果時,如何調用 API。 謝謝!
這是 API 我正在使用https://www.themealdb.com/api/json/v1/1/search.php?s=Steak
這是我的 url 在開發模式 http://localhost:3000/search/steak/。
我想在 getStaticProps 中傳遞“牛排”,並在我的組件中傳遞 getStaticProps 的結果。
export const getStaticProps = async () => {
const res = await axios.get(
'https://www.themealdb.com/api/json/v1/1/search.php?s=Steak'
);
return {
props: {
meals: res.data,
},
};
};
我認為你做不到。 GetStaticProps
在構建時呈現頁面,因此您無法根據用戶請求呈現頁面。 我建議您閱讀此文檔的“何時應該使用 GetStaticProps”部分。 您可以使用反應狀態或GetServerSideProps
(閱讀相同的文檔)。 您還可以使用GetStaticPath
靜態呈現一堆頁面並傳遞,例如,10 個最常搜索的食物。
如果您使用動態路由,則可以使用getStaticPaths執行此操作。
您可以在基於文件的路由中使用search/[slug].js
作為動態路由。
然后,在[slug].js
中,您將擁有如下內容:
export default function Page({ response }) {
return <div>{JSON.stringify(response)})</div>
}
// get all the possible paths for the individual ingredients
export async function getStaticPaths() {
const data = await axios.get(
'www.themealdb.com/api/json/v1/1/list.php?i=list'
);
return {
paths: data.meals.map((ingredient) => ({
params: { slug: ingredient.strIngredient.toString().toLowerCase. },
})),
fallback: false, // can also be true or 'blocking'
}
}
export async function getStaticProps({ params }) {
const { slug } = params
const response = await axios.get(
`https://www.themealdb.com/api/json/v1/1/search.php?s=${slug}`
);
return {
props: {
response
},
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.