【问题标题】:Next.js - How to pass id from query to getInitialProps functionNext.js - 如何将 id 从查询传递到 getInitialProps 函数
【发布时间】:2020-06-26 05:15:19
【问题描述】:

我想用来自 db 的文章建立一个简单的网站。我的问题是我需要用服务器渲染这些文章,我可以使用 Next.js 文档中的 getInitialProps 函数来完成它:https://nextjs.org/docs/api-reference/data-fetching/getInitialProps#getinitialprops-for-older-versions-of-nextjs

现在它工作正常,但我想实现通过它的 ID 获取文章,我的链接应该是这样的:

http://localhost:3000/articles/<some_id>

我已经这样做了,但现在我想读取该 ID 并将其传递给 getInitialProps 函数,以便仅为一篇特定文章调用我的 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 作为参数得到 context 对象,它上面有 query。你有自定义服务器还是使用了 next 的 [param] 页面?
  • 我只使用外部 API 没有任何服务器
  • 是的,它正在工作我错过了那个上下文参数:) 感谢您的回答

标签: javascript reactjs next.js fetch router


【解决方案1】:

getInitialProps 作为参数获取context 对象,其中包含query

你应该在那里获得你的价值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-05
    • 1970-01-01
    • 2019-11-21
    • 2022-01-09
    • 1970-01-01
    • 2016-12-31
    • 2020-04-27
    相关资源
    最近更新 更多