fix: hydration mismatch (loading spinner restart) + cache strategy
Root cause of loading spinner restarting / name appearing twice:
React hydration mismatch → whole tree regenerated. Fixed all sources:
- AppProvider: remove typeof window in useState init (SSR/client diff);
read cached forum name in useEffect instead
- ToastProvider: remove createPortal(document.body) (SSR absent →
mismatch)
- LoadingScreen: name container uses dangerouslySetInnerHTML('') so
React never manages/clobbers the inline-script-filled text
- layout.js: inline script moved to body first child (React official
anti-FOUC pattern)
Cache: dynamic pages/API no-cache + ETag (304 on revalidate); static
/_next/static assets immutable 1y. Verified: 304 + immutable headers.
This commit is contained in:
1 parent
517661441a
commit
024b678ad3
6 files changed
+58
-72
No files matched your search
+19
-33
@@ -13,41 +13,27 @@ export default function RootLayout({ children }) {
|
|||||||
return (
|
return (
|
||||||
<html lang="zh-CN" suppressHydrationWarning>
|
<html lang="zh-CN" suppressHydrationWarning>
|
||||||
<head>
|
<head>
|
||||||
{/* 首帧前同步主题,避免深色模式闪白(FOUC):手动设置优先,否则跟随系统 */}
|
|
||||||
<script
|
|
||||||
dangerouslySetInnerHTML={{
|
|
||||||
__html: `(function(){
|
|
||||||
try {
|
|
||||||
var t = localStorage.getItem('forumlify-theme');
|
|
||||||
if (!t) {
|
|
||||||
t = (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) ? 'dark' : 'light';
|
|
||||||
}
|
|
||||||
document.documentElement.setAttribute('data-theme', t);
|
|
||||||
} catch (e) {}
|
|
||||||
// 论坛名:有缓存立即写入 <title>(第二次访问首帧即显示),无缓存保持 Loading...
|
|
||||||
try {
|
|
||||||
var n = localStorage.getItem('forumlify-forum-name');
|
|
||||||
if (n) document.title = n;
|
|
||||||
} catch (e) {}
|
|
||||||
// 加载页名字:DOMContentLoaded(早于 React hydrate)时把缓存名填入,
|
|
||||||
// 二次访问首帧就显示论坛名,不必等 React 启动
|
|
||||||
document.addEventListener('DOMContentLoaded', function () {
|
|
||||||
try {
|
|
||||||
var n2 = localStorage.getItem('forumlify-forum-name');
|
|
||||||
if (n2) {
|
|
||||||
var el = document.getElementById('loadingTitle');
|
|
||||||
if (el && !el.textContent) {
|
|
||||||
el.textContent = n2;
|
|
||||||
document.title = n2;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (e) {}
|
|
||||||
});
|
|
||||||
})();`,
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
|
{/* 首帧初始化(主题防 FOUC + 论坛名首帧显示):
|
||||||
|
script 放 body 首个子元素(children 前),React 官方防 FOUC 模式 */}
|
||||||
|
<script dangerouslySetInnerHTML={{ __html: `(function(){
|
||||||
|
try {
|
||||||
|
var t = localStorage.getItem('forumlify-theme');
|
||||||
|
if (!t) { t = (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) ? 'dark' : 'light'; }
|
||||||
|
document.documentElement.setAttribute('data-theme', t);
|
||||||
|
} catch (e) {}
|
||||||
|
try { var n = localStorage.getItem('forumlify-forum-name'); if (n) document.title = n; } catch (e) {}
|
||||||
|
document.addEventListener('DOMContentLoaded', function () {
|
||||||
|
try {
|
||||||
|
var n2 = localStorage.getItem('forumlify-forum-name');
|
||||||
|
if (n2) {
|
||||||
|
var el = document.getElementById('loadingTitle');
|
||||||
|
if (el && !el.textContent) { el.textContent = n2; document.title = n2; }
|
||||||
|
}
|
||||||
|
} catch (e) {}
|
||||||
|
});
|
||||||
|
})();` }} />
|
||||||
<ToastProvider>
|
<ToastProvider>
|
||||||
<CustomCssLoader />
|
<CustomCssLoader />
|
||||||
{children}
|
{children}
|
||||||
|
|||||||
+1
-1
@@ -27,7 +27,7 @@ function HomeInner() {
|
|||||||
|
|
||||||
// 初始化未完成:显示全屏加载页,避免未加载完的界面闪烁
|
// 初始化未完成:显示全屏加载页,避免未加载完的界面闪烁
|
||||||
if (!ready) {
|
if (!ready) {
|
||||||
return <LoadingScreen forumName={forumName} forumNameLoaded={forumNameLoaded} />;
|
return <LoadingScreen />;
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|||||||
+15
-16
@@ -12,13 +12,9 @@ export function useApp() {
|
|||||||
|
|
||||||
export default function AppProvider({ children }) {
|
export default function AppProvider({ children }) {
|
||||||
const [currentUser, setCurrentUser] = useState(null);
|
const [currentUser, setCurrentUser] = useState(null);
|
||||||
// 初始化时先用 localStorage 缓存的论坛名,避免闪烁(默认名 → 正确名)
|
// 固定初始值(SSR/客户端一致,避免 hydration mismatch 导致加载圈重启);
|
||||||
const [forumName, setForumName] = useState(() => {
|
// 缓存论坛名由 useEffect 读取,首帧显示靠内联脚本(body 首个子元素)
|
||||||
if (typeof window !== 'undefined') {
|
const [forumName, setForumName] = useState('Forumlify');
|
||||||
return localStorage.getItem('forumlify-forum-name') || 'Forumlify';
|
|
||||||
}
|
|
||||||
return 'Forumlify';
|
|
||||||
});
|
|
||||||
const [theme, setThemeState] = useState('light');
|
const [theme, setThemeState] = useState('light');
|
||||||
const [view, setView] = useState('feed'); // feed | post | new | admin | settings | messages | user | custom
|
const [view, setView] = useState('feed'); // feed | post | new | admin | settings | messages | user | custom
|
||||||
const [currentPostId, setCurrentPostId] = useState(null);
|
const [currentPostId, setCurrentPostId] = useState(null);
|
||||||
@@ -27,14 +23,8 @@ export default function AppProvider({ children }) {
|
|||||||
const [sort, setSort] = useState('latest');
|
const [sort, setSort] = useState('latest');
|
||||||
const [refreshKey, setRefreshKey] = useState(0);
|
const [refreshKey, setRefreshKey] = useState(0);
|
||||||
const [ready, setReady] = useState(false); // 初始加载完成标记(控制加载页/淡入)
|
const [ready, setReady] = useState(false); // 初始加载完成标记(控制加载页/淡入)
|
||||||
// 有缓存论坛名即视为"已加载"(第二次访问立即显示缓存名,不必等服务器);
|
// 固定 false(避免 hydration mismatch);有缓存时由 useEffect 立即置 true
|
||||||
// 首次访问无缓存 → 等服务器返回后才显示名字
|
const [forumNameLoaded, setForumNameLoaded] = useState(false);
|
||||||
const [forumNameLoaded, setForumNameLoaded] = useState(() => {
|
|
||||||
if (typeof window !== 'undefined') {
|
|
||||||
return !!localStorage.getItem('forumlify-forum-name');
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
});
|
|
||||||
const loadedRef = useRef(false);
|
const loadedRef = useRef(false);
|
||||||
|
|
||||||
const refresh = useCallback(() => setRefreshKey((k) => k + 1), []);
|
const refresh = useCallback(() => setRefreshKey((k) => k + 1), []);
|
||||||
@@ -68,8 +58,17 @@ export default function AppProvider({ children }) {
|
|||||||
});
|
});
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
// 初始化:恢复登录、加载论坛名
|
// 初始化:读取缓存论坛名(立即显示),恢复登录、加载服务器论坛名
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
// 缓存论坛名(hydrate 后立即生效,首帧显示由内联脚本完成)
|
||||||
|
try {
|
||||||
|
const cached = localStorage.getItem('forumlify-forum-name');
|
||||||
|
if (cached) {
|
||||||
|
setForumName(cached);
|
||||||
|
setForumNameLoaded(true);
|
||||||
|
}
|
||||||
|
} catch (e) {}
|
||||||
|
|
||||||
if (loadedRef.current) return;
|
if (loadedRef.current) return;
|
||||||
loadedRef.current = true;
|
loadedRef.current = true;
|
||||||
|
|
||||||
|
|||||||
@@ -1,19 +1,15 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
// 全屏加载页:初始化未完成时显示转圈,加载完成后淡出
|
// 全屏加载页:初始化未完成时显示转圈,加载完成后淡出
|
||||||
// - 名字容器总是渲染(空):layout.js 内联脚本会在 DOMContentLoaded(早于
|
// - 名字容器用 dangerouslySetInnerHTML(空):React 完全不管理其文本内容,
|
||||||
// React hydrate)时把缓存的论坛名填入,实现二次访问首帧即显示名字
|
// 内联脚本(body 首个子元素,DOMContentLoaded)填入缓存名后不会被 React
|
||||||
// - 首次访问无缓存:由 React 在收到服务器论坛名后淡入显示
|
// 检测/重写 → 无 hydration mismatch,加载圈不会重启,名字不会二次出现
|
||||||
export default function LoadingScreen({ forumName, forumNameLoaded }) {
|
export default function LoadingScreen() {
|
||||||
return (
|
return (
|
||||||
<div className="loading-screen">
|
<div className="loading-screen">
|
||||||
<div className="loading-inner">
|
<div className="loading-inner">
|
||||||
<div className="loading-spinner" />
|
<div className="loading-spinner" />
|
||||||
{/* suppressHydrationWarning: 内联脚本会在 hydrate 前填入缓存名,
|
<div className="loading-title loading-title-appear" id="loadingTitle" dangerouslySetInnerHTML={{ __html: '' }} />
|
||||||
避免 React 检测到文本不匹配而重写 DOM(名字二次出现/转圈重启) */}
|
|
||||||
<div className="loading-title loading-title-appear" id="loadingTitle" suppressHydrationWarning>
|
|
||||||
{forumNameLoaded && forumName}
|
|
||||||
</div>
|
|
||||||
<div className="loading-sub">加载中...</div>
|
<div className="loading-sub">加载中...</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
+9
-11
@@ -2,8 +2,9 @@
|
|||||||
|
|
||||||
// Toast 通知系统:右上角弹出,自动消失(替代 alert)
|
// Toast 通知系统:右上角弹出,自动消失(替代 alert)
|
||||||
// 用法:const { toast } = useToast(); toast('发布成功', 'success');
|
// 用法:const { toast } = useToast(); toast('发布成功', 'success');
|
||||||
|
// 注意:不用 createPortal(SSR 时 document 不存在会造成 hydration mismatch,
|
||||||
|
// 导致整树重建)。toast-container 是 position:fixed,渲染位置不影响视觉。
|
||||||
import { createContext, useContext, useState, useCallback, useRef } from 'react';
|
import { createContext, useContext, useState, useCallback, useRef } from 'react';
|
||||||
import { createPortal } from 'react-dom';
|
|
||||||
|
|
||||||
const ToastContext = createContext(null);
|
const ToastContext = createContext(null);
|
||||||
|
|
||||||
@@ -35,16 +36,13 @@ export function ToastProvider({ children }) {
|
|||||||
return (
|
return (
|
||||||
<ToastContext.Provider value={{ toast }}>
|
<ToastContext.Provider value={{ toast }}>
|
||||||
{children}
|
{children}
|
||||||
{typeof document !== 'undefined' && createPortal(
|
<div className="toast-container">
|
||||||
<div className="toast-container">
|
{toasts.map((t) => (
|
||||||
{toasts.map((t) => (
|
<div key={t.id} className={'toast toast-' + t.type} onClick={() => dismiss(t.id)}>
|
||||||
<div key={t.id} className={'toast toast-' + t.type} onClick={() => dismiss(t.id)}>
|
{t.message}
|
||||||
{t.message}
|
</div>
|
||||||
</div>
|
))}
|
||||||
))}
|
</div>
|
||||||
</div>,
|
|
||||||
document.body
|
|
||||||
)}
|
|
||||||
</ToastContext.Provider>
|
</ToastContext.Provider>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
+9
-2
@@ -8,13 +8,20 @@ const nextConfig = {
|
|||||||
{ source: '/uploads/:name', destination: '/api/uploads/:name' },
|
{ source: '/uploads/:name', destination: '/api/uploads/:name' },
|
||||||
];
|
];
|
||||||
},
|
},
|
||||||
// 论坛是动态内容:HTML 页面不缓存,避免 CDN/浏览器拿到旧版本
|
// 缓存策略:动态页面/API no-cache(浏览器每次验证 → 304);
|
||||||
|
// 静态资源(_next/static)immutable 长缓存(Next.js 默认,但需在 no-cache 之后覆盖)
|
||||||
async headers() {
|
async headers() {
|
||||||
return [
|
return [
|
||||||
{
|
{
|
||||||
source: '/:path*',
|
source: '/:path*',
|
||||||
headers: [
|
headers: [
|
||||||
{ key: 'Cache-Control', value: 'no-cache, no-store, must-revalidate' },
|
{ key: 'Cache-Control', value: 'no-cache, must-revalidate' },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
source: '/_next/static/:path*',
|
||||||
|
headers: [
|
||||||
|
{ key: 'Cache-Control', value: 'public, max-age=31536000, immutable' },
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|||||||
Reference in new issue
Block a user