【问题标题】:NextJS get query outside component [duplicate]NextJS 获取组件外的查询
【发布时间】:2021-12-23 12:58:02
【问题描述】:

我有 getServerSideProps 函数从 API 获取数据:

export async function getServerSideProps() {
  const res = await fetch(
    `https://www.thecocktaildb.com/api/json/v1/1/search.php?s=${queryCocktailName}`
  )
  const data = await res.json()
  return {
    props: { data },
  }
}

我需要在这个函数中获取查询,( /search/queryCocktailName/ ) 我试过const {query} = useRouter() 但正如 NextJS 所说:只能在函数组件的主体内部调用 Hooks

这个组件位置:search/[id].tsx

【问题讨论】:

标签: reactjs next.js fetch


【解决方案1】:

这应该可行:

import { GetServerSidePropsContext } from "next";

export async function getServerSideProps({
  params
}: GetServerSidePropsContext<{ id: string }>) {
  const res = await fetch(
    `https://www.thecocktaildb.com/api/json/v1/1/search.php?s=${params?.id}`
  );
  const data = await res.json();
  return {
    props: { data }
  };
}

See docsgetServerSideProps 获取context 对象作为第一个参数,它包含params 字段,该字段应包含id 字段,因为您的文件名为[id].tsx

编辑:更改为 TypeScript 版本。

【讨论】:

  • 是的,谢谢。但是在打字稿中我应该使用什么类型?
  • 编辑了答案。没注意到你使用 TypeScript。
  • 如果以上代码有效,请将其标记为解决方案。谢谢
  • 它有效,谢谢。
【解决方案2】:

每个getServerSideProps 都有上下文,由req 和res 组成。

export async function getServerSideProps({req, res}) {
  const { url = "" } = req || {};
  //url will have the query of your route like :: url =  /search/queryCocktailName/

  const res = await fetch(
    `https://www.thecocktaildb.com/api/json/v1/1/search.php?s=${queryCocktailName}`
  )
  const data = await res.json()
  return {
    props: { data },
  }
}

以上代码适用于您的用例

【讨论】:

    猜你喜欢
    • 2023-04-07
    • 2021-04-10
    • 2022-01-26
    • 2022-01-10
    • 2022-01-13
    • 2017-03-20
    • 2021-02-14
    • 2021-10-08
    • 2020-11-06
    相关资源
    最近更新 更多