在 TypeScript 和 Reactjs 中我的界面中的对象数组出现问题
Troubles with array of objects inside my interface in TypeScript & Reactjs
我开始将我的代码转换为 TypeScript,但由于某种原因我无法开始工作。
代码没有报错但是没有显示列表。
type song = {
id: number,
artist: string,
titre: string;
links: string[] | number,
has_youtube_link: number,
has_picture: number,
hour: number,
minutes: number,
votes: number
}
interface Songs {
listOfSongs: song[]
}
const LastPlayedSongs: React.FC = () => {
const [songs, setSong] = useState<Songs | null>(null)
useEffect(() => {
fetch("APILink")
.then(response => response.json())
.then(response => {
setSong(response);
})
.catch(err => {
console.log(err);
});
}, [])
return (
<>
<ul>
{songs?.listOfSongs?.map((song) => (
<li key={song.id}>{song.titre}, {song.id}</li>
))}
</ul>
</>
);
}
如果我直接使用歌曲类型而不是歌曲界面就可以了。
type song = {
id: number,
artist: string,
titre: string;
links: string[] | number,
has_youtube_link: number,
has_picture: number,
hour: number,
minutes: number,
votes: number
}
const LastPlayedSongs: React.FC = () => {
const [songs, setSong] = useState<song[] | null>(null)
useEffect(() => {
fetch("APILink")
.then(response => response.json())
.then(response => {
setSong(response);
})
.catch(err => {
console.log(err);
});
}, [])
return (
<>
<ul>
{songs?.map((song) => (
<li key={song.id}>{song.titre}, {song.id}</li>
))}
</ul>
</>
);
}
有谁知道如何让第一个成功或提供一些关于我做错了什么的信息。
亲切的问候
您应该再次更改界面或将状态正确设置为对象属性。
type Songs = song []
然后 useState<Songs>([])
然后 setSong(response)
- 你现在的界面是什么
setSong({listOfSongs:response})
最好不要让你的状态可以为空,它是一个数组,最初可以是一个空数组
我开始将我的代码转换为 TypeScript,但由于某种原因我无法开始工作。
代码没有报错但是没有显示列表。
type song = {
id: number,
artist: string,
titre: string;
links: string[] | number,
has_youtube_link: number,
has_picture: number,
hour: number,
minutes: number,
votes: number
}
interface Songs {
listOfSongs: song[]
}
const LastPlayedSongs: React.FC = () => {
const [songs, setSong] = useState<Songs | null>(null)
useEffect(() => {
fetch("APILink")
.then(response => response.json())
.then(response => {
setSong(response);
})
.catch(err => {
console.log(err);
});
}, [])
return (
<>
<ul>
{songs?.listOfSongs?.map((song) => (
<li key={song.id}>{song.titre}, {song.id}</li>
))}
</ul>
</>
);
}
如果我直接使用歌曲类型而不是歌曲界面就可以了。
type song = {
id: number,
artist: string,
titre: string;
links: string[] | number,
has_youtube_link: number,
has_picture: number,
hour: number,
minutes: number,
votes: number
}
const LastPlayedSongs: React.FC = () => {
const [songs, setSong] = useState<song[] | null>(null)
useEffect(() => {
fetch("APILink")
.then(response => response.json())
.then(response => {
setSong(response);
})
.catch(err => {
console.log(err);
});
}, [])
return (
<>
<ul>
{songs?.map((song) => (
<li key={song.id}>{song.titre}, {song.id}</li>
))}
</ul>
</>
);
}
有谁知道如何让第一个成功或提供一些关于我做错了什么的信息。
亲切的问候
您应该再次更改界面或将状态正确设置为对象属性。
type Songs = song []
然后useState<Songs>([])
然后setSong(response)
- 你现在的界面是什么
setSong({listOfSongs:response})
最好不要让你的状态可以为空,它是一个数组,最初可以是一个空数组