2

我已经制作了 Hacker News Search 的副本,但是当我进入我的网站时,我无法显示 API 中的所有故事。根本没有故事出现。我必须在搜索栏上输入一些内容才能全部显示。

我已经使用 axios 获取了数据,我console.log收集了数据,并且似乎已成功获取数据,因为我可以在控制台上看到该集合。

github 仓库:https ://github.com/vnsteven/hacker-news-react

网站:https ://vnsteven.github.io/hacker-news-react/

我的 App.js 文件 (src/containers/App.js) 的开头:

import React, { Component } from 'react';

import Navbar from '../components/Navbar/Navbar';
import Footer from '../components/Footer/Footer';
import Items from '../components/Items/Items';
import './App.css';
import axios from './axios-hn.js';

class App extends Component {
  state = {
    list: [],
    initialList: [],
    favoriteList: [],
    count: 0,
    favoriteCount: 0
  };

  async componentDidMount() {
    try {
      const fetchingData = await axios.get('topstories.json');
      const itemIds = await fetchingData.data;
      const list = [];
      itemIds.forEach((id) => {
        axios.get(`item/${id}.json`).then((res) =>
          list.push({
            id: res.data.id,
            title: res.data.title,
            score: res.data.score,
            url: res.data.url,
            author: res.data.by
          })
        );
      });
      this.setState({ initialList: list });
    } catch (err) {
      console.error(err);
    }
  }
4

1 回答 1

4

以下是如何使用“HackerNews API”的示例:

首先,TopStories端点返回一个 post 列表ids。然后,您需要将每个解析id为自己的post. 为了简化这一点,您可以利用Promise.allAPI。此方法promises在输入数组中提供的所有内容自行解析时解析。

我也在使用“React Hooks”来处理状态变化。看看如何使用useStateuseEffect钩子处理状态。

无论如何,这是代码示例:

https://codesandbox.io/embed/hackernews-top-10-posts-h73km

于 2019-08-02T14:12:53.557 回答