在react中从不同端口获取数据时出现问题-

问题描述 投票:0回答:1

我正在尝试获取数据并在浏览器上显示,但收到错误“notes.map 不是函数”。

import { useEffect, useState } from 'react';
import { Note as NoteModel } from './models/note';
import NoteComponent from './component/NoteComponent';

function App() {
  const [notes, setNotes] = useState<NoteModel[]>([]);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    const loadNotes = async () => {
      try {
        setIsLoading(true);
        const response = await fetch("/api/notes", { method: "GET" });
        const notes : [] = await response.json();
        setNotes(notes);
        console.log(notes);
      } catch (error) {
        console.error(error);
        alert(error);
      } finally {
        setIsLoading(false); 
      }
    };
    loadNotes();
  },[]);

  return (
    <div className="App">
      {
        notes.map(note => (
          <NoteComponent note={note} key={note._id}/>
        ))
      }
    </div>
  );
}

export default App;

我可以通过“JSON.stringyfy(notes)”显示数据,但我想在组件中显示数据。

reactjs typescript
1个回答
0
投票

当你这样做时

JSON.stringyfy(notes)
它是一个对象还是一个数组?
也许您从 API 中获得了这样的对象
{ notes: [...]}
,并且您首先必须从该对象中提取数组

© www.soinside.com 2019 - 2024. All rights reserved.