我有两页: index.js和other.js,在index.js中有一个方法getServerSideProps;
export async function getServerSideProps(context)
{
//code here
}我想在other.js页面中使用相同的函数。因为index.js getServerSideProps中的代码相当长,所以我不得不将index.js中的getServerSideProps导入到other.js中,这样做如下;
import { getServerSideProps } from "./index";
...
export { getServerSideProps };它可以正常工作,但问题是,我想在getServerSideProps中提出另一个只在other.js页面中运行的请求。其中一种方法是复制我为getServerSideProps编写的index.js代码,并将其粘贴到other.js中并修改代码。问题是,正如我前面提到的,代码在getServerSideProps中非常庞大,我不想复制它并将其粘贴到我需要的所有页面中。
我的问题是,如何在我已经从另一个页面导出的getServerSideProps中添加另一个。基本上,我希望将index.js中导出的getServerSideProps合并到本地的other.js中
发布于 2022-04-10 02:02:29
如果您想重用相同的getServerSideProps函数,但根据调用该函数的页面有条件地运行特定代码,则可以尝试使用context.req对象:
index.js
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
import { getServerSideProps } from "./index";
export default function Other({ data }) {
return <>{data}</>;
}
export { getServerSideProps };https://stackoverflow.com/questions/71812273
复制相似问题