[英]Next.js - How to pass id from query to getInitialProps function
I want to build a simple website with articles from db.我想用db中的文章建立一个简单的网站。 My problem is that I need these articles to be rendered with server and I can do it with getInitialProps
function from Next.js documentation: https://nextjs.org/docs/api-reference/data-fetching/getInitialProps#getinitialprops-for-older-versions-of-nextjs我的问题是我需要使用服务器呈现这些文章,我可以使用 Next.js 文档中的getInitialProps
函数来完成: https ://nextjs.org/docs/api-reference/data-fetching/getInitialProps#getinitialprops-for -older-versions-of-nextjs
For now It's working properly but I want to implement getting article by its ID and my link should be like that:现在它工作正常,但我想通过它的 ID 实现获取文章,我的链接应该是这样的:
http://localhost:3000/articles/<some_id>
I have done that but now I want to read that ID and pass it to getInitialProps function to call my API for only one specific article.我已经这样做了,但现在我想读取该 ID 并将其传递给 getInitialProps 函数,以便仅为一篇特定文章调用我的 API。 My problem is that I don't know how to pass down router
props to get that ID from query and call API.我的问题是我不知道如何传递router
道具以从查询和调用 API 中获取该 ID。
import { withRouter } from "next/router";
import fetch from "isomorphic-unfetch";
const Article = ({ router }) => {
console.log(router);
return (
<div>
<h1>Hello World</h1>
</div>
);
};
Article.getInitialProps = async props => {
console.log(props);
const res = await fetch(
`https://admin.jozefrzadkosz-portfolio.pl/articles/${router.query.id}`
);
const articles = await res.json();
return { articles };
};
export default withRouter(Article);
getInitialProps
get as an argument context
object, which has query
on it. getInitialProps
作为参数context
对象获取,该对象上有query
。
You should get your value in there.你应该在那里得到你的价值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.