【发布时间】:2021-01-31 02:00:57
【问题描述】:
我开始将我的代码转换为 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>
</>
);
}
有谁知道如何使第一个工作或提供一些关于我做错了什么的信息。
亲切的问候
【问题讨论】:
-
可以添加repsonse的console.log吗?
-
@Domino987 这是一个像这样的简单数组:
(14) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}] 0: {id: 21520, artist: "Blondie", titre: "Rapture", links: "<a href="https://geo.itunes.apple.com/be/album/rap…:110px;height:40px;background-size:contain;"></a>", has_youtube_link: "0", …} -
类型和接口都应该使用大写字母。它使区分变量和类型变得更加容易。
-
@LindaPaiste 感谢您的建议,将更改并避免这样做。
标签: reactjs typescript array.prototype.map