![](/img/trans.png)
[英]Next.js routing: pushing a new route from a slug page doesn't route properly
[英]Next.js doesn't return slug with useRouter in console log
我在 Next.js 中使用动态路由器,这是代码
import { useRouter } from "next/router";
const exampleFunction = () => {
const router = useRouter();
const {slug} = router.query;
console.log(slug);
return (
<h1>{slug}</h1>
);
};
export default exampleFunction;
该文件的位置是:
lms/client/pages/teacher/course/test/[slug].js
当我访问这样的链接时:
http://localhost:3000/teacher/course/test/testmw
我可以看到 slug 正在浏览器中呈现; 但是,当我查看控制台时,我在 slug 的实际值之前看到了undefined
值。
我想知道这是我做错了什么还是 Next.js 的预期行为?
有人向我提出了类似的问题。 但是,答案主要是关于在服务器端获取路由,我想知道我是否可以在客户端有效地做同样的事情。
“查询:对象 - 解析为对象的查询字符串。如果页面没有数据获取要求,则在预渲染期间它将是一个空对象。默认为 {}”
最初,“查询”对象将是 {},因此“slug”将是未定义的。 这是你应该做的:
return (
{slug && <h1>slug</h1>}
);
如果未定义“slug”,则不渲染元素。
要解决这个问题,需要使用“getServerSideProps”获取服务器上的“slug”,并将其传递给组件:
export const getServerSideProps = async (context) => {
const { slug } = context.query;
// If slug is "undefined", since "undefined" cannot be serialized, server will throw error
// But null can be serializable
if (!slug) {
slug = null;
}
// now we are passing the slug to the component
return { props: { slug:slug } };
};
现在你的组件有props.slug
。
const exampleFunction = (props) => {
const {slug}=props // you could just pass {slug} to the component
return (
{slug && <h1>slug</h1>}
);
};
export default exampleFunction;
它首先显示未定义,因为在第一次渲染时不可能从路由中获取查询。 我假设您将在第二次渲染后获得 slug 的实际值。 你做得很好,这是 next.js 的行为。 您可以查看getStaticpaths或者您可以使用Effect来检查查询是否已加载并根据需要执行您的任务
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.