Next.js中Router.push传递对象显示undefined的问题
问题原因与解决方案
核心原因
Next.js 的 Router.push 中,query 参数本质对应 URL 的查询字符串,而 URL 查询参数仅支持字符串、数字这类简单可序列化类型。直接传递对象时,Next.js 会把对象强制转为字符串 "[object Object]",但接收页面解析 router.query 时,无法自动将该字符串还原为对象,甚至在部分路由场景下会直接丢弃无效的非字符串参数,最终导致 obj 变成 undefined。
你提到其他页面用相同方法传递对象没问题,大概率是那些页面实际使用了路由 state(而非直接放在 query 中),或是误将序列化后的字符串当成了直接传对象。
两种解决方案
方案1:JSON序列化对象(适合需要在URL保留数据的场景)
将对象转为JSON字符串传递,接收时再解析回对象:
发送页面(Recipes.jsx)修改:
function sendProps() { Router.push({ pathname: "/favorites", query: { obj: JSON.stringify(obj), // 把对象序列化为JSON字符串 a, }, }); }
接收页面(Favorites.jsx)修改:
import { useRouter } from "next/router"; export default function Favorites() { const router = useRouter(); const { query: { obj: objStr, a }, } = router; // 解析JSON字符串,同时处理可能的解析错误 const obj = objStr ? JSON.parse(objStr) : null; console.log(a); console.log(obj); return <div><h1>Recipe</h1></div>; }
方案2:使用路由state传递(适合无需暴露在URL中的数据)
Router.push 的第三个参数支持传递 state,这部分数据不会出现在URL中,仅在客户端路由跳转时有效:
发送页面(Recipes.jsx)修改:
function sendProps() { Router.push( { pathname: "/favorites", query: { a } }, // 字符串仍放query undefined, // 跳过as参数 { state: { obj } } // 把对象放在state里 ); }
接收页面(Favorites.jsx)修改:
import { useRouter } from "next/router"; export default function Favorites() { const router = useRouter(); const { a } = router.query; const { obj } = router.state || {}; // 从state中读取对象 console.log(a); console.log(obj); return <div><h1>Recipe</h1></div>; }
注意:路由state仅在客户端跳转时有效,如果用户刷新接收页面,
router.state会变为undefined,因为state不会存储在服务端或URL中。
内容的提问来源于stack exchange,提问作者chickenwings123
相关产品推荐
相关产品推荐

