反应获取和显示数据问题

时间:2020-03-27 19:43:19

标签: reactjs fetch

我是新来的反应者,尝试练习时遇到了一个问题。 我想从Hacker News获取数据,并显示内容。

好吧,提取部分是好的,我得到了想要的内容。但是,当我尝试显示它时,什么也没有发生。如果我记录了内容,则可以看到它,但是无法以HTML显示它。

有人对此有想法吗?

这是代码

setUrls () {

        // Define API base URL
        let baseUrl = "https://hacker-news.firebaseio.com/v0/item/";

        // IDs of stories
        const ids = [22694891,22693792,22696252,22697212,22695174,22660888,22689301,22695264];

        // Empty Array for content
        const cards = []

        for (let i = 0; i < ids.length; i++){
            fetch(baseUrl + ids[i] + ".json")
            .then(response => response.json())
            .then((data) => {
                cards.push(data);  
            })
        }
        this.setState({
            cards: cards
        })
    }

    componentDidMount () {
        this.setUrls();
    }

    render() {
        let cards = this.state.cards;
        console.log(cards)

        return (
            cards.map(card => {
                return (
                    <div>{card.id}</div>
                )
            })
        )
    }

在render()中,当我记录状态时可以看到它,但是HTML为空。

1 个答案:

答案 0 :(得分:2)

我重构了您的代码。试试吧。

setUrls () {
    // Define API base URL
    let baseUrl = "https://hacker-news.firebaseio.com/v0/item/";

    // IDs of stories
    const ids = [
      22694891,
      22693792,
      22696252,
      22697212,
      22695174,
      22660888,
      22689301,
      22695264,
    ];
    
    ids.forEach((id) => {
      fetch(`${baseUrl}${id}.json`)
        .then(response => response.json())
        .then((data) => {
          this.setState(({ cards }) => ({
            cards: [ ...cards, data ]
          }));
        })
        .catch(({ message }) => {
          console.error(message);
        });
    });
}

componentDidMount () {
    this.setUrls();
}

render() {
    const { cards } = this.state;

    return (
        cards.map(card => (
          <div>{card.id}</div>
        ))
    )
}

相关问题