[英]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.