【发布时间】:2020-08-17 05:03:49
【问题描述】:
在 Next.js 9.3 中,我需要在初始渲染时访问查询并将查询结果传递给 next/head 以更改页面的标题和描述。
我的组件正在从 useRouter 挂钩获取查询。不幸的是,查询对象在初始渲染时是{ amp: undefined }。在初始渲染之后,立即发生另一个渲染,并且它具有所有必需的细节。我开始使用这个解决方法来检查路由是否准备好https://github.com/zeit/next.js/issues/8259#issuecomment-544912889,但这不适用于next/head,因为值将是未定义的。
import React from 'react';
import { useRouter } from 'next/router';
import Head from 'next/head';
function isRouterReady(router) {
return router.asPath !== router.route;
}
export default Component = () => {
const router = useRouter();
const { query } = router;
useEffect(() => {
if (isRouterReady(router)) {
// router.query is populated here with name
}
}, [query]);
return (
<Head>
// query has only amp key, but not my name
<title>{query.name}</title>
<meta
name="description"
content={query.name}
/>
</Head>
);
};
有什么方法可以正确地将路由器查询中的值传递给next/head 的标题和元描述?
【问题讨论】:
标签: javascript reactjs next.js