我正在尝试获取数据并在浏览器上显示,但收到错误“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)”显示数据,但我想在组件中显示数据。
当你这样做时
JSON.stringyfy(notes)
它是一个对象还是一个数组? { notes: [...]}
,并且您首先必须从该对象中提取数组