首页 > 解决方案 > 使用 HackerNews API 对 API 的请求进行分页

问题描述

***问题很简单,我只是写了很多具体的。***

我在网上找了几个小时,似乎找不到答案。大多数分页是在您收到来自 API 调用的数据之后,或者用于使用它自己的服务器构建的后端 node.js。

我的问题,我有一个返回 500 个 ID 数组的 API 请求。然后是第二个多 API 调用,循环通过每个 ID 进行承诺 API 调用。我使用 Promise.all 方法。完成此请求需要 2-3 分钟。

目前,我做了一个快速过滤器来获得前十个结果,所以它会显示出来,我可以渲染数据以处理其他事情,比如渲染组件和样式。

我的问题是,我希望能够在 API 调用仍在进行时对数据进行分页。

基本上,Promise.all 发送一个包含 10 个 ID(十个 API 调用)的数组,不断获取。但是在第一组十个之后,我想开始接收要渲染的数据。

现在,我的过滤方法只能得到十个。或者等待 2-3 分钟让所有 500 个渲染。

这是我的 request.js 文件,(它是我的 App 组件的一部分,为了清楚起见,我只是将其分开)。

    import axios from 'axios';
    import BottleNeck from 'bottleneck'

    const limiter = new BottleNeck({
      maxConcurrent: 1, 
      minTime: 333
    })


    export const Request = (setResults, searchBarType, setLoading) => {
      
      const searchBar = type => {
        const obj = {
          'new': 'newstories',
          'past': '',
          'comments': 'user',
          'ask': 'askstories',
          'show': 'showstories',
          'jobs': 'jobstories',
          'top': 'topstories',
          'best': 'beststories',
          'user': 'user'
        }
      
        return obj[type] ? obj[type] : obj['new'];
      }

      let type = searchBar(searchBarType)

      const getData = () => {
        const options = type
        const API_URL = `https://hacker-news.firebaseio.com/v0/${options}.json?print=pretty`;

        return new Promise((resolve, reject) => {
          return resolve(axios.get(API_URL))
        })
      }

      const getIdFromData = (dataId) => {
        const API_URL = `https://hacker-news.firebaseio.com/v0/item/${dataId}.json?print=pretty`;
        return new Promise((resolve, reject) => {
          return resolve(axios.get(API_URL))
        })
      }


      const runAsyncFunctions = async () => {
        setLoading(true)
        const {data} = await getData()
        let firstTen = data.filter((d,i) => i < 10);

        Promise.all(
          firstTen.map(async (d) => {
            const {data} = await limiter.schedule(() => getIdFromData(d))
            console.log(data)
            return data;
          })
          )
          .then((newresults) => setResults((results) => [...results, ...newresults]))
          setLoading(false)
        // make conditional: check if searchBar type has changed, then clear array of results first
      }  
      

      runAsyncFunctions()
    }
      
    

并提供帮助,这是我的 App.js 文件

    import React, { useState, useEffect } from 'react';
    import './App.css';
    import { SearchBar } from './search-bar';
    import { Results } from './results';
    import { Request } from '../helper/request'
    import { Pagination } from './pagination';

    function App() {
      const [results, setResults] = useState([]);
      const [searchBarType, setsearchBarType] = useState('news');
      const [loading, setLoading] = useState(false);
      const [currentPage, setCurrentPage] = useState(1);
      const [resultsPerPage] = useState(3);
      

      // Select search bar button type 
      const handleClick = (e) => {
        const serachBarButtonId = e.target.id;
        console.log(serachBarButtonId)
        setsearchBarType(serachBarButtonId)
      }
      
      // API calls
      useEffect(() => {
        Request(setResults, searchBarType, setLoading)
      }, [searchBarType])

      // Get current results 
      const indexOfLastResult = currentPage * resultsPerPage;
      const indexOfFirstResult = indexOfLastResult - resultsPerPage;
      const currentResults = results.slice(indexOfFirstResult, indexOfLastResult);

      // Change page
      const paginate = (pageNumber) => setCurrentPage(pageNumber); 


      return (
        <div className="App">
          <SearchBar handleClick={handleClick} />
          <Results results={currentResults} loading={loading} />
          <Pagination resultsPerPage={resultsPerPage} totalResults={results.length} paginate={paginate} />
        </div>
      );
    }

    export default App;

我希望它是通用的,足以遵循指导方针。请问我任何事情以帮助澄清。我花了 8-10 个小时搜索并尝试解决这个问题......

标签: reactjsapipaginationpromise.all

解决方案


您可以继续使用过滤器,但您必须进行一些更改,对于组件Pagination的totalResults道具,您必须设置 500 行,以便用户可以选择他想要的页面,因为如果您设置 10 行,用户可以选择的页面是1,2,3,4,但我们不需要将所有页面 1 到 34 页,因为我们有 500 个 id。第二点,我们需要逐页从服务器获取数据,页面大小等于 3 我们需要传递给 Request startIndexlastIndex给 Request。

请求.js

import axios from 'axios';
    import BottleNeck from 'bottleneck'

    const limiter = new BottleNeck({
      maxConcurrent: 1, 
      minTime: 333
    })


    export const Request = (setResults, searchBarType, setLoading, startIndex, lastIndex) => {
      
      const searchBar = type => {
        const obj = {
          'new': 'newstories',
          'past': '',
          'comments': 'user',
          'ask': 'askstories',
          'show': 'showstories',
          'jobs': 'jobstories',
          'top': 'topstories',
          'best': 'beststories',
          'user': 'user'
        }
      
        return obj[type] ? obj[type] : obj['new'];
      }

      let type = searchBar(searchBarType)

      const getData = () => {
        const options = type
        const API_URL = `https://hacker-news.firebaseio.com/v0/${options}.json?print=pretty`;

        return new Promise((resolve, reject) => {
          return resolve(axios.get(API_URL))
        })
      }

      const getIdFromData = (dataId) => {
        const API_URL = `https://hacker-news.firebaseio.com/v0/item/${dataId}.json?print=pretty`;
        return new Promise((resolve, reject) => {
          return resolve(axios.get(API_URL))
        })
      }


      const runAsyncFunctions = async () => {
        setLoading(true)
        const {data} = await getData()
        let ids = data.slice(firstIndex, lastIndex+1) // we select our ids by index

        Promise.all(
          ids.map(async (d) => {
            const {data} = await limiter.schedule(() => getIdFromData(d))
            console.log(data)
            return data;
          })
          )
          .then((newresults) => setResults((results) => [...results, ...newresults]))
          setLoading(false)
        // make conditional: check if searchBar type has changed, then clear array of results first
      }  
      

      runAsyncFunctions()
    }
      
    

应用程序.js

import React, { useState, useEffect } from 'react';
    import './App.css';
    import { SearchBar } from './search-bar';
    import { Results } from './results';
    import { Request } from '../helper/request'
    import { Pagination } from './pagination';

    function App() {
      const [results, setResults] = useState([]);
      const [searchBarType, setsearchBarType] = useState('news');
      const [loading, setLoading] = useState(false);
      const [currentPage, setCurrentPage] = useState(1);
      const [resultsPerPage] = useState(3);
      

      // Select search bar button type 
      const handleClick = (e) => {
        const serachBarButtonId = e.target.id;
        console.log(serachBarButtonId)
        setsearchBarType(serachBarButtonId)
      }
      
      // API calls
      useEffect(() => {
        Request(setResults, searchBarType, setLoading, 0, 2) //we fetch the first 3 articles
      }, [searchBarType])

     

      // Change page
      const paginate = (pageNumber) => {
           // Get current results 
          const indexOfLastResult = currentPage * resultsPerPage;
          const indexOfFirstPost = indexOfLastResult - resultsPerPage;
          Request(setResults, searchBarType, setLoading, indexOfFirstPost , indexOfLastResult) //we fetch the 3 articles of selected page
          setCurrentPage(pageNumber); 
      }


      return (
        <div className="App">
          <SearchBar handleClick={handleClick} />
          <Results results={results} loading={loading} />
          <Pagination resultsPerPage={resultsPerPage} totalResults={500} paginate={paginate} />
        </div>
      );
    }

    export default App;

推荐阅读