【发布时间】:2020-09-13 11:24:39
【问题描述】:
我从 Next.js 开始,在浏览文档后,我无法弄清楚如何在 getStaticPaths 方法中获取路由参数 code,如下所示!?。 code 以任何方式事先都不知道,它可以是任何东西。
我不想调用 api 并在组件内部使用 useEffect 获取数据。
文件:pages/post/[code].js
import React from 'react';
import apiCall from 'api/something';
export default ({post}) => {
return <>
render components here based on prop `post`
</>
}
export async function getStaticPaths() {
// How to get [code] from the route here, which can be used below?
return {
paths: // NEED [code] HERE from current route,
fallback: false
}
}
export async function getStaticProps(ctx) {
return {
props: {
// [ctx.code] resolved from current route with the help of getStaticPaths,
post: apiCall(ctx.code)
}
}
}
我试过 getServerSideProps 对我有用:
export const getServerSideProps = async (ctx) => {
return {
props: {
post: await apiCall(ctx.query.code)
}
};
};
但是当我做next export 声明时它失败了:
无法导出带有
getServerSideProps的页面。在此处查看更多信息:https://err.sh/next.js/gssp-export
在进一步调查此错误I found this solution 后,这对我来说是不可行的,因为我的应用托管在 Heroku 上。
我正在尝试根据路由参数code 在服务器端渲染 html 以及数据。但现在做不到。
【问题讨论】:
-
你没有在 getStaticProps 中得到 ctx.code 吗??
-
@pritesh 我使用了
getServerSideProps,但在next export上失败了
标签: javascript reactjs next.js server-side-rendering