You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next14+TypeScript中Layout.tsx无法读取LocalStorage值的问题

问题分析

Next.js 14 默认的 Layout 是服务器组件,服务器端运行时无法访问浏览器的 localStorage API,所以你代码里的 if (typeof window !== "undefined") 代码块在服务器渲染阶段完全不会执行。另外,redirect 函数只能在服务器组件或服务器动作中使用,客户端组件里直接调用会报错。

解决方案

要实现需求,需要把 Layout 改为客户端组件,并使用客户端导航 API 处理跳转:

  1. 添加 'use client' 指令,将组件转为客户端组件
  2. 使用 useRouter 和 useEffect 来读取 localStorage 并执行跳转
  3. 增加加载状态避免页面闪屏

修改后的代码示例:

'use client';
import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';

export default function SetupLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const router = useRouter();
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    const isLogin = localStorage.getItem('isLogin');
    if (isLogin === 'yes') {
      router.push('/dashboard');
    } else {
      router.push('/sign-in');
    }
    setIsLoading(false);
  }, [router]);

  // 加载过程中可以显示加载动画或空白
  if (isLoading) {
    return <div>Loading...</div>;
  }

  return <>{children}</>;
}
额外说明
  • 客户端组件中必须用 useRouter 的 push/replace 方法做导航,不能用服务器端的 redirect 函数
  • 初始加载状态很重要,否则会短暂渲染原页面内容后再跳转,影响用户体验
  • 如果需要更严谨的身份验证,建议结合服务器端会话(比如NextAuth.js),避免仅依赖客户端存储的敏感信息

内容的提问来源于stack exchange,提问作者Ahmad Alfan Juniyanto

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 08:59:54