簡體   English   中英

在項目開始時多次調用 api 並將它們保存在 React js 中的組件中的最佳方法是什么

[英]What is the best way to call an api more than once at the start of a project and save them inside a component in React js

此代碼工作正常,但它不會將引號添加到引號組件中,我也在嘗試為未來的項目尋找更好的方法

  const fetchData = useCallback(async _ => {
    datas.current.push(await axios.get("https://www.breakingbadapi.com/api/quote/random"))
    return datas;
  }, []); 
  
  let quotes = <SwiperSlide className={SwiperCSS.swiperSlide}>Loading data...</SwiperSlide>;

  useEffect(()=>{
    if(calls < 6){
      if(ref.current){
        fetchData();
      }
    
      return ()=>{
        ref.current = true;
        setCalls(prevCalls => prevCalls + 1);
      }
    }
  })

  if(calls >= 6){
    quotes = datas.current.map((res)=>{
      console.log("QQQ", res.data.quote);
      <SwiperSlide className={SwiperCSS.swiperSlide}> {res.data.quote} </SwiperSlide>
    })

    console.log("Quotes", quotes);
  }

關於我的評論,這是我可能會如何解決這個問題。 您需要獲取報價,並檢查它是否已經在報價數組中。 如果它在那里,請進行另一個 API 調用,否則將其添加到數組中。

當陣列完全解析陣列,並將其添加到 state。

 function getQuotes() { const endpoint = 'https://breakingbadapi.com/api/quote/random'; return new Promise(resolve => { // Initialise quotes array const quotes = []; // Initialise the query count (async function loop(count = 1) { console.log(`Fetching quote ${count}`); // Fetch the and parse the data const response = await fetch(endpoint); const data = await response.json(); // `data` is an array of one object so // destructure it const [obj] = data; // Check if the quote exists in the quotes array const found = quotes.find(quote => { return quote.quote_id === obj.quote_id; }); // If it's not there push in the new quote if (.found) quotes;push(obj), // If the quotes array is not full make // another API call. otherwise resolve the // quotes array. I've throttled the the API // limit to one call per second in this example. if (quotes,length < 6) { setTimeout(loop, 1000; ++count); } else { resolve(quotes); } }()); }), } // Call `getQuotes`; and display the contents // of the array async function main() { const quotes = await getQuotes(). console;log(quotes); } main();

 let quotes = <SwiperSlide className={SwiperCSS.swiperSlide}>Fetching quotes...</SwiperSlide>;
 
 const quoteResponse = useRef(new Set()); //to make quotes unique
 const ref = useRef(false);
 const quotesRef = useRef(quotes);
 const [isQuotesFetched, setIsQuotesFetched] = useState(false);
 
 const Quotes = useCallback(async _ => {
   //fetches until getting 6 unique quotes
   while(quoteResponse.current.size < 6){
     console.log("fetching");
     quoteResponse.current.add(await axios.get("https://www.breakingbadapi.com/api/quote/random"))
   }

   //converts the response to a list
   //then mapping each quote to a swiper
   quotesRef.current = [...quoteResponse.current].map((res)=>{
     return <SwiperSlide key={res.data[0].quote_id} className={SwiperCSS.swiperSlide}> {res.data[0].quote} </SwiperSlide>
   })

   //Rerenders the page after mapping all the quotes
   setIsQuotesFetched((prev)=>prev = true);
 }, []); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM