我正在尝试添加一个链接以将用户重定向到创建页面, 但是当我单击链接时,出现以下错误:
TypeError: Cannot read properties of undefined (reading 'cookies')
链接代码 :
<Link href={link}>Add New Employee</Link>
getInitialProps//_app.tsx
MyApp.getInitialProps = async (context: any) => {
const {req, res, pathname} = context.ctx;
const {language, auth_key} = req.cookies;
return {
lang: language ?? 'ar',
token: auth_key ?? null,
}
};
您必须在MyApp.getInitialProps
内编写同构代码,因为该代码可以在服务器(在第一个页面加载期间)或客户端(在客户端导航期间)上运行。
从getInitialProps
文档中:
对于初始页面加载,
getInitialProps
将在服务器上运行 只。 然后,getInitialProps
将在导航到 通过next/link
组件或使用next/router
的不同路由。 但是,如果在自定义_app.js
中使用getInitialProps
,并且页面 被导航到实现getServerSideProps
,然后getInitialProps
将在服务器上运行。
这是一个可能的实现,可以解决您的错误。它在访问req.cookies
之前检查是否定义了req
。如果是,则改为从document
中检索 Cookie。
// Get cookie from `document` on the client-side
const getCookie = (name) => {
const match = document.cookie?.match(new RegExp(`(^| )${name}=([^;]+)`));
return match?.[2];
};
MyApp.getInitialProps = async (context) => {
const { req } = context.ctx;
const language = req ? req.cookies.language : getCookie('language');
const auth_key = req ? req.cookies.auth_key : getCookie('auth_key');
return {
lang: language ?? 'ar',
token: auth_key ?? null,
}
};