【问题标题】:paginating requests to an API, using HackerNews API使用 HackerNews API 对 API 的请求进行分页
【发布时间】:2021-05-24 06:02:42
【问题描述】:

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

我已经在网上搜索了几个小时,但似乎找不到答案。大多数分页是在您收到来自 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 个小时搜索并尝试解决这个问题...

【问题讨论】:

    标签: reactjs api pagination promise.all


    【解决方案1】:

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

    【讨论】:

    • 因此,这为页面提供了更多按钮,但是,主要问题仍未解决......它将数组中的前 3 个切片用于 API 调用。然后一遍又一遍地返回它。我需要它一次返回 10 个,并且一次在 id 数组中继续返回 10 个下一个,直到完成所有 500 个。这就是问题所在。
    • 在 indexOfLastResult 的参数中更改 (...0,2),indexOfFirstResut,然后向 useEffect 数组“currentPage”添加第二个依赖项。我相信它有效......所以谢谢你
    猜你喜欢
    • 1970-01-01
    • 2016-08-12
    • 2017-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-14
    • 1970-01-01
    相关资源
    最近更新 更多