首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何组合多个getServerSideProps函数

如何组合多个getServerSideProps函数
EN

Stack Overflow用户
提问于 2022-04-09 22:11:20
回答 1查看 361关注 0票数 1

我有两页: index.js和other.js,在index.js中有一个方法getServerSideProps

代码语言:javascript
复制
export async function getServerSideProps(context) 
{
   //code here
}

我想在other.js页面中使用相同的函数。因为index.js getServerSideProps中的代码相当长,所以我不得不将index.js中的getServerSideProps导入到other.js中,这样做如下;

代码语言:javascript
复制
import { getServerSideProps } from "./index";
...
export { getServerSideProps };

它可以正常工作,但问题是,我想在getServerSideProps中提出另一个只在other.js页面中运行的请求。其中一种方法是复制我为getServerSideProps编写的index.js代码,并将其粘贴到other.js中并修改代码。问题是,正如我前面提到的,代码在getServerSideProps中非常庞大,我不想复制它并将其粘贴到我需要的所有页面中。

我的问题是,如何在我已经从另一个页面导出的getServerSideProps中添加另一个。基本上,我希望将index.js中导出的getServerSideProps合并到本地的other.js中

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-04-10 02:02:29

如果您想重用相同的getServerSideProps函数,但根据调用该函数的页面有条件地运行特定代码,则可以尝试使用context.req对象:

index.js

代码语言:javascript
复制
export default function Home({ data }) {
  return <>{data}</>;
}

export async function getServerSideProps(context) {
  let foo;

  // Parse `message.url` into parts. An alternative to using the `URL` class
  // would be to use `context.resolvedUrl`, but that will take more effort to
  // isolate pathnames when query parameters are involved.
  const reqUrl = new URL(
    context.req.url,
    `https://${context.req.headers.host}`
  );
  const thisPage = reqUrl.pathname;
  const queryParams = reqUrl.searchParams;

  switch (thisPage) {
    case "/":
      // code for index.js
      foo = "Hello, index.js!";
      break;

    case "/other":
      // code for other.js
      foo = "Hello, other.js!";
      break;

    default:
      foo = "Hello, world!";
  }

  // common code
  console.log("`thisPage`:", thisPage);
  console.log("`context.resolvedUrl`:", context.resolvedUrl);
  console.log("`queryParams`:", queryParams);

  return {
    props: { data: foo },
  };
}

other.js

代码语言:javascript
复制
import { getServerSideProps } from "./index";

export default function Other({ data }) {
  return <>{data}</>;
}

export { getServerSideProps };
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71812273

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档