微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用 HackerNews API 对 API 请求进行分页

如何解决使用 HackerNews API 对 API 请求进行分页

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

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

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

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

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

基本上,Promise.all 发送一个包含 10 个 id(10 个 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,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 个小时搜索并试图解决这个问题...

解决方法

您可以继续使用您的过滤器,但您必须进行一些更改,对于组件 PaginationtotalResults 道具,您必须设置 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()
    }
      
    

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,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,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;

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。