我有一个简单的
app/components/organisms/Cookies.tsx
模态窗口组件,我将其导入到app/page.tsx
中。我在组件顶部添加了'use client'
指令,但出现了以下错误:ReferenceError: localStorage未定义
我的Cookies.tsx
代码:
'use client';
import { useState } from 'react';
const Cookies = () => {
const localStorageCookies = localStorage.getItem('cookies-accepted');
const [cookiesAccepted, setCookiesStatus] = useState<boolean>(!!localStorageCookies);
const acceptCookies = () => {
localStorage.setItem('cookies-accepted', 'true');
setCookiesStatus(true);
}
return (
<>
{!cookiesAccepted && (
<section className="fixed max-w-md p-4 mx-auto bg-white border border-gray-200 left-12 bottom-16 rounded-2xl z-20">
<h2 className="font-semibold text-gray-800 "> Cookie Notice</h2>
<p className="mt-4 text-sm text-gray-600">
We use cookies to ensure that we give you the best experience on our
website.{' '}
<a href="#" className="text-blue-500 hover:underline">
Read cookies policies
</a>
.{' '}
</p>
<div className="flex items-center justify-between mt-4 gap-x-4 shrink-0">
<button className="text-xs text-gray-800 underline transition-colors duration-300 hover:text-gray-600 focus:outline-none">
Manage your preferences
</button>
<button
className=" text-xs bg-gray-900 font-medium rounded-lg hover:bg-gray-700 text-white px-4 py-2.5 duration-300 transition-colors focus:outline-none"
onClick={acceptCookies}
>
Accept
</button>
</div>
</section>
)}
</>
);
};
export default Cookies;
我做错了什么?我试图将 Cookies.tsx
放在 app
文件夹之外,但没有帮助。
我正在使用的是 Next.js 版本 13.4.1
。
'use client'
指令的组件仍会得到服务器端渲染(这就是导致错误的原因)。任何访问 Web API(如localStorage
)的逻辑都需要在useEffect
中完成。 - juliomalves