属性在类型"从不"上不存在。(使用打字稿对映射的 JSON 服务器数据使用状态)



我正在学习mui的react教程,并决定加入typescript

参考:网络忍者MUI

备注.tsx

获取JSON服务器数据,然后将其设置为notes

import React, { useEffect, useState } from 'react';
const Notes = () => {
const [notes, setNotes] = useState([]);
useEffect(() => {
fetch('http://localhost:8000/notes')
.then((res) => res.json())
.then((data) => setNotes(data));
}, []);

此处映射JSON服务器伪数据

return (
<div>
{notes.map((note:string) => (
<p key={note.id}>{note.title}</p>
))}
</div>
);
};
export default Notes;

db.json(json服务器伪数据(

{
"notes": [
{
"title": "Yoshi's birthday bash",
"details": "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.",
"category": "reminders",
"id": 1
},
{
"title": "Complete my ninja training",
"details": "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took.",
"category": "work",
"id": 2
},
{
"title": "Order a pizza!",
"details": "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.nLorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.",
"category": "todos",
"id": 3
}
]
}

这是出现的错误

您需要键入notes对象,并告诉您的组件本地状态以期待它以及您的map函数,请参阅下面的一些指针。

import React, { useEffect, useState } from 'react';
type Note = {
title: string,
details: string,
category: "reminders" | "work" | "todos",
id: number,
}
const Notes = () => {
const [notes, setNotes] = useState<Note[]>([]);
useEffect(() => {
fetch('http://localhost:8000/notes')
.then((res) => res.json())
.then((data: Note[]) => setNotes(data));
}, []);
return (
<div>
{notes.map((note: Note) => (
<p key={note.id}>{note.title}</p>
))}
</div>
);
};
export default Notes;