使用Next.js 13获取数据时遇到React子元素错误
问题修复方案
错误原因分析
- 接口数据结构不匹配:你调用的
https://jsonplaceholder.typicode.com/todos/接口直接返回数组,而非包含items字段的对象,data?.items会返回undefined,后续map操作引发异常。 - Pages Router的async组件限制:如果你的项目用Next.js 13的Pages Router(非App Router),页面组件不能是
async函数,直接返回Promise会触发Objects are not valid as a React child错误。
修复步骤
方案1:适配接口返回结构
修改getNotes函数,直接返回接口返回的数组:
async function getNotes() { const res = await fetch('https://jsonplaceholder.typicode.com/todos/') if (!res.ok) { throw new Error('Failed to fetch data'); } const data = await res.json(); return data as any[]; // 直接返回接口返回的数组 }
方案2:Pages Router环境适配
Pages Router不支持async页面组件,可选择以下两种方式获取数据:
服务端获取(getServerSideProps)
function Page({ notes }) { return ( <> <h1>hello</h1> <div className='results'> <div className='results'> {notes.map((note) => ( <div key={note.id}>{note.title}</div> ))} </div> </div> </> ) } export async function getServerSideProps() { const res = await fetch('https://jsonplaceholder.typicode.com/todos/') if (!res.ok) { return { notFound: true } } const notes = await res.json(); return { props: { notes } } } export default Page;
客户端获取(useEffect)
import { useState, useEffect } from 'react'; export default function Page() { const [notes, setNotes] = useState([]); const [loading, setLoading] = useState(true); useEffect(() => { async function fetchNotes() { const res = await fetch('https://jsonplaceholder.typicode.com/todos/') if (!res.ok) { console.error('Failed to fetch data'); return; } const data = await res.json(); setNotes(data); setLoading(false); } fetchNotes(); }, []); if (loading) { return <div>Loading...</div>; } return ( <> <h1>hello</h1> <div className='results'> <div className='results'> {notes.map((note) => ( <div key={note.id}>{note.title}</div> ))} </div> </div> </> ) }
验证
修复后页面会正常渲染每条todo的标题,不再出现[object Promise]相关错误。
内容的提问来源于stack exchange,提问作者StackUnderFlow
相关产品推荐
相关产品推荐

