如何在next-redux-wrapper的wrapper.getServerSideProps中获取param或query?
如何在wrapper的getServerSideProps中获取query/params
你的问题出在getServerSideProps的回调参数解构上——你没有从context里取出query或params,而是错误地从store或req中查找这些值。
修正后的代码
const Home = () => { const router = useRouter(); const { id } = router.query; return <div>{id}</div>; }; export const getServerSideProps = wrapper.getServerSideProps( (store) => async ({ req, res, query, params }) => { // 解构出query和params console.log(query.id); // 正常获取URL查询参数或动态路由参数 console.log(params.id); // 仅动态路由场景可用,对应[ id ].js中的id } );
关键说明
- Next.js的
getServerSideProps会传入一个context对象,其中**query包含URL上的所有查询参数**,如果是动态路由页面(如pages/[id].js),params会包含动态路由的参数。 store对象本身不直接持有query/params,req对象上也不会默认挂载这些属性——这些值必须从context参数中解构获取。- 前端组件里用
router.query能拿到值,是因为客户端Router对象封装了这些信息,但服务端的getServerSideProps需要从context中直接读取。
内容的提问来源于stack exchange,提问作者Yoo Guk
相关产品推荐
相关产品推荐

