Next.js 13 中如何全局配置 SWRConfig?
在Next.js 13 App目录下全局配置SWRConfig的正确方式
你之前报错是因为<SWRConfig>是React组件,只能放在<body>标签内部的React上下文里,不能包裹<html>标签。正确的做法是把它放在<body>里,包裹所有需要共享SWR配置的内容,包括导航栏和页面子组件。
修改后的RootLayout代码如下:
import './globals.css'; import '@/styles/bootstrap.min.css'; // 保留原项目需要的bootstrap样式 import { Inter } from 'next/font/google'; import Navbar from '@/components/Navbar'; import { SWRConfig } from 'swr'; const inter = Inter({ subsets: ['latin'] }); export const metadata = { title: 'Create Next App', description: 'Generated by create next app', }; export default function RootLayout({ children }) { return ( <html lang="en"> <body className={inter.className}> <SWRConfig value={{ fetcher: async (url) => { const res = await fetch(url); // 处理非200-299状态码的请求 if (!res.ok) { const error = new Error('An error occurred while fetching the data.'); error.info = await res.json(); error.status = res.status; throw error; } return res.json(); }, }} > <Navbar /> <br /> {children} </SWRConfig> </body> </html> ); }
这样配置后,App目录下所有页面和组件都会自动继承这个全局的SWR fetcher配置,无需重复编写错误处理逻辑。
内容的提问来源于stack exchange,提问作者Shivam Sangwan
相关产品推荐
相关产品推荐

