簡體   English   中英

我可以使用兩個 useEffect 並在 map 中包含 map

[英]Can I use two useEffect and have map inside a map

我是 React 的新手,希望對以下問題有所幫助。 我目前有這段代碼。

 import React, { useState, useEffect } from "react";

function FetchData() {
  const [repos, setRepos] = useState([]);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    fetch("https://api.github.com/orgs/org_name/repos")
      .then((res) => res.json())
      .then((data) => {
        setRepos(data);
      })
      .then(() => {
        setIsLoading(false);
      })
      .catch((err) => console.log(err));
  }, []);

return (
    <div>
      {repos.map((repo) => (
        <div key={repo.id}>
          <div>
            <h2>Name: {repo.name}</h2>
            <p>Top 5 Contributors</p>
))}

我上面的代碼工作正常,但我現在的問題是我想將前 5 位貢獻者添加到存儲庫並訪問我必須訪問 go 到https://api.github.com/repos/org_name/{repos}/contributors ,為此,我首先必須使用repo.contributor_url我應該使用另一個useEffectmap來顯示前 5 個貢獻者嗎?

編輯
基本上我想做這樣的事情。

useEffect(() => {
    fetch(`${repos.contributors_url}`)
      .then((res) => res.json())
      .then((data) => {
        setContributors(data);
        console.log(data);
      })
      .catch((err) => console.log(err));
  }, []);
...
<p> Top 5 Contributors: </p>
 <ul>
   {contributors.map((c, i) => {
   <li key={i}>{c.name}</li>
   )}
 </ul>

因為你是 React 的新手。 React 曾經有基於 class 的組件來處理 state,而那些基於 class 的組件具有稱為生命周期方法的特殊功能。 但是從React 16.8開始,React Community 提出了React-Hooks ,功能組件現在可以用來處理 state, useState() 和 useEffect()就是 Hooks 的例子。

現在單獨使用useEffect()來執行生命周期方法的工作。

您在代碼中使用useEffect()的方式是模擬componentDidMount() ,因為您將第二個參數保留為空數組[]

我們可以使用其他生命周期方法,如componentDidUpdate()comp.netnWillUnmount()使用useEffect() Hook 本身。

然后根據您的要求,您可以根據組件的需要多次使用 useEffect() Hook。

現在來更新您的問題的一部分:

所以,你基本上需要做promise chaining 我們知道fetch()是基於 promise 的,所以當一個異步調用被解析並且我們得到第一個數據時,僅在您的useEffect()掛鈎中,您需要使用第二個 url-end 點進行另一個異步請求以獲取相應的數據。

這是現在更新的代碼:試試這個

import React, { useState, useEffect } from 'react';

function FetchData() {
  const [repos, setRepos] = useState([]);
  const [isLoading, setIsLoading] = useState(true);

  const [contributors, setContributors] = useState([]);
  const [isContributorLoading, setIsContributorLoading] = useState(true);

  useEffect(() => {
    fetch('https://api.github.com/orgs/{org}/repos')
      .then((res) => res.json())
      .then((data) => {
        setRepos(data); // Data 1(repos) is received
        // Now We make another API call to get Data 2 (contributors)
        return fetch('https://api.github.com/repos/{org}/{repos}/contributors');
      })
      .then((res) => res.json()) // Chaining promise,handling 2nd Fetch request
      .then((data2) => {
        console.log(data2);
        setContributors(data2);
       })
      .then(() => {
        setIsLoading(false);
      })
      .catch((err) => console.log(err));
  }, []);


  return (
    <div>
      { repos.length && repos.map((repo) => (
        <div key={repo.id}>
          <div>
            <h2>Name: {repo.name}</h2>
          </div>
        </div>
      ))}

      <p> Top 5 Contributors: </p>
         <ul>
           {contributors.length && contributors.map((c, i) => {
             return <li key={i}>{c.name}</li>
           )}
          </ul>
    </div>
  );
}

所以,基本上你現在需要學習更多關於如何使用 Hook 的知識,尤其是useEffect() 做一些谷歌搜索,如果我現在告訴你一切都不好。 那就試一試吧。

你可以直接在一個useEffect里面調用apis。

 import React, { useState, useEffect } from "react"; function App() { const [repos, setRepos] = useState([]); const [contributor, setContributor] = useState([]); const [isLoading, setIsLoading] = useState(true); useEffect(() => { async function caller() { try { setIsLoading(true); const response = await fetch( "https://api.github.com/orgs/octokit/repos" ); const result = await response.json(); const contri = []; console.log(result); result.forEach((item) => { contri.push(fetch(`${item.contributors_url}`)); }); Promise.all(contri).then((contributorResults) => contributorResults).then((responses) => { console.log(responses); return Promise.all(responses.map((r) => r.json())); }).then((cont) => { setContributor([...cont]) }); setRepos(result); } catch (err) { console.log(err); } finally { setIsLoading(false); } } caller(); }, []); return ( <div> {repos.map((repo,index) => ( <div key={repo.id}> <h2> Name: {repo.name} </h2> { contributor[`${index}`] && contributor[`${index}`].slice(0,5).map(item => { return <div key={item.id}> <div>{item.login}</div> </div> })} </div> ))} {isLoading && <div>...loading</div>} </div> ); } export default App;

暫無
暫無

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

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