使用Next.js 13获取数据时出错

mfuanj7w  于 2022-12-23  发布在  其他
关注(0)|答案(1)|浏览(202)

当我尝试使用Next.js 13获取一些JSON数据时,我一直收到以下错误:

Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.

我只是想打印出JSON获取的标题。不确定是什么原因导致了这个问题:

async function getNotes() {
      const res = await fetch('https://jsonplaceholder.typicode.com/todos/')
      const data = await res.json();
      
      return data?.items as any[];
    }
    
    export default async function Page() {
    
      const notes = await getNotes();
    
      return (
        <>
          <h1>hello</h1>
          <div className='results'>
            <div className='results'>
              {notes.map((note) => (
                <div key={note.id}>{note.title}</div>
              ))}
            </div>
          </div>
        </>
      ) 
    }
euoag5mw

euoag5mw1#

您正在尝试将Promise对象呈现为React组件的子级

async function getNotes() {
  const res = await fetch('https://jsonplaceholder.typicode.com/todos/');
  const data = await res.json();

  return data?.items as any[];
}

function NoteList() {
  const [notes, setNotes] = useState([]);

  useEffect(() => {
    async function fetchNotes() {
      const notes = await getNotes();
      setNotes(notes);
    }

    fetchNotes();
  }, []);

  return (
    <div className='results'>
      {notes.map((note) => (
        <div key={note.id}>{note.title}</div>
      ))}
    </div>
  );
}

相关问题