Next.js13中「Objects are not valid as a React child」错误修复
修复Next.js 13 Pages Router中async页面组件导致的React子元素错误
错误原因
Next.js 13的Pages Router不支持将页面组件定义为async函数(App Router支持该特性)。当你把Home组件写成async function时,React会将这个组件视为Promise对象尝试渲染,这直接触发了"objects are not valid as a React child"错误——React无法直接渲染Promise对象。
修复方案
在Pages Router中,需使用Next.js提供的服务器端数据获取方法(getServerSideProps或getStaticProps)获取数据,再传递给页面组件。
修改后的完整代码
import Header from "@/components/Header"; import Navbar from "@/components/Navbar"; import RestaurantCard from "@/components/Restaurantcard"; import { PrismaClient, Restaurant } from "@prisma/client"; const prisma = new PrismaClient() // 页面组件改为普通函数,接收props中的数据 export default function Home({ restaurants }: { restaurants: Restaurant[] }) { console.log({restaurants}) return ( <main className="bg-gray-100 min-h-screen"> <main className="max-w-screen-2xl m-auto bg-white"> <Navbar /> <main> <Header /> <div className="py-3 px-36 mt-10 flex flex-wrap justify-center"> {/* 给RestaurantCard传递餐厅数据props,并添加React列表渲染必需的key */} {restaurants.map((res) => ( <RestaurantCard key={res.id} restaurant={res} /> ))} </div> </main> </main> </main> ); } // 使用getServerSideProps在服务器端获取数据,传递给页面组件 export async function getServerSideProps() { const restaurants = await prisma.restaurant.findMany(); return { props: { restaurants }, // 传递给页面组件的props }; }
额外注意事项
- 给
RestaurantCard添加了key属性(使用餐厅id),这是React列表渲染的强制要求,可避免控制台警告。 - 给
RestaurantCard传递了restaurantprops,你需要在Restaurantcard.tsx中接收该props并使用(例如渲染餐厅名称)。 - 若餐厅数据不频繁变动,可替换
getServerSideProps为getStaticProps,后者会在构建时生成静态页面,性能更优。
内容的提问来源于stack exchange,提问作者Sahil
相关产品推荐
相关产品推荐

