【问题标题】:Troubles with array of objects inside my interface in TypeScript & Reactjs我的 TypeScript 和 Reactjs 界面中的对象数组出现问题
【发布时间】: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: "&lt;a href="https://geo.itunes.apple.com/be/album/rap…:110px;height:40px;background-size:contain;"&gt;&lt;/a&gt;", has_youtube_link: "0", …}
  • 类型和接口都应该使用大写字母。它使区分变量和类型变得更加容易。
  • @LindaPaiste 感谢您的建议,将更改并避免这样做。

标签: reactjs typescript array.prototype.map


【解决方案1】:

您应该再次更改界面或将状态正确设置为对象属性。

  1. type Songs = song [] 然后useState&lt;Songs&gt;([]) 然后setSong(response)
  2. 你目前拥有的接口然后setSong({listOfSongs:response})

最好不要让你的状态为空,它是一个数组,最初可以是一个空数组

【讨论】:

  • 这两个选项确实有效,但您会推荐哪一个?一个比另一个好?
  • 好吧,如果状态只是为了保留响应,我们不需要引入新属性。所以我会说第一种方法更好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-05
  • 1970-01-01
  • 2019-06-17
  • 2023-02-05
  • 2016-11-26
相关资源
最近更新 更多