我可以使用两个 useEffect 并在地图中包含地图吗

我是 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 位贡献者添加到存储库中,并访问我必须访问的内容,https://api.github.com/repos/org_name/{repos}/contributors并且要访问它,我首先必须使用repo.contributor_url 是否应该使用另一个useEffect和map显示前 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>


临摹微笑
浏览 133回答 2
2回答

白板的微信

由于您是 React 新手。React 曾经使用基于类的组件来处理状态,并且这些基于类的组件具有称为生命周期方法的特殊函数。但从React 16.8开始,React 社区提出了React-Hooks,功能组件现在可以用来处理状态,useState() 和 useEffect()是 Hooks 的例子。现在useEffect()单独用于执行生命周期方法的工作。您在代码中使用useEffect() 的方式是模拟componentDidMount(),因为您将第二个参数保留为空数组[]我们可以使用useEffect()&nbsp;Hook 本身来使用其他生命周期方法,例如componentDidUpdate()和componetnWillUnmount() 。然后根据您的要求,您可以根据组件的需要多次使用 useEffect() Hook。现在来更新你的问题的部分:所以,你基本上需要进行承诺链。我们知道fetch()是基于 Promise 的,因此当一个异步调用得到解决并且我们仅在useEffect()挂钩内获取第一个数据时,您需要使用第二个 url 端点发出另一个异步请求来获取相应的数据数据。这是现在更新的代码:试试这个import React, { useState, useEffect } from 'react';function FetchData() {&nbsp; const [repos, setRepos] = useState([]);&nbsp; const [isLoading, setIsLoading] = useState(true);&nbsp; const [contributors, setContributors] = useState([]);&nbsp; const [isContributorLoading, setIsContributorLoading] = useState(true);&nbsp; useEffect(() => {&nbsp; &nbsp; fetch('https://api.github.com/orgs/{org}/repos')&nbsp; &nbsp; &nbsp; .then((res) => res.json())&nbsp; &nbsp; &nbsp; .then((data) => {&nbsp; &nbsp; &nbsp; &nbsp; setRepos(data); // Data 1(repos) is received&nbsp; &nbsp; &nbsp; &nbsp; // Now We make another API call to get Data 2 (contributors)&nbsp; &nbsp; &nbsp; &nbsp; return fetch('https://api.github.com/repos/{org}/{repos}/contributors');&nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; .then((res) => res.json()) // Chaining promise,handling 2nd Fetch request&nbsp; &nbsp; &nbsp; .then((data2) => {&nbsp; &nbsp; &nbsp; &nbsp; console.log(data2);&nbsp; &nbsp; &nbsp; &nbsp; setContributors(data2);&nbsp; &nbsp; &nbsp; &nbsp;})&nbsp; &nbsp; &nbsp; .then(() => {&nbsp; &nbsp; &nbsp; &nbsp; setIsLoading(false);&nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; .catch((err) => console.log(err));&nbsp; }, []);&nbsp; return (&nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; { repos.length && repos.map((repo) => (&nbsp; &nbsp; &nbsp; &nbsp; <div key={repo.id}>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <h2>Name: {repo.name}</h2>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; ))}&nbsp; &nbsp; &nbsp; <p> Top 5 Contributors: </p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<ul>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{contributors.length && contributors.map((c, i) => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return <li key={i}>{c.name}</li>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;)}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </ul>&nbsp; &nbsp; </div>&nbsp; );}所以,基本上你现在需要更多地了解如何使用 Hooks 特别是useEffect() 。做一些谷歌搜索,如果我现在告诉你一切就不好了。那就试一试吧。

千万里不及你

可以直接调用一个useEffect内部的api。import React, { useState, useEffect } from "react";function App() {&nbsp; const [repos, setRepos] = useState([]);&nbsp; const [contributor, setContributor] = useState([]);&nbsp; const [isLoading, setIsLoading] = useState(true);&nbsp; useEffect(() => {async function caller() {&nbsp; try {&nbsp; &nbsp; setIsLoading(true);&nbsp; &nbsp; const response = await fetch(&nbsp; &nbsp; &nbsp; "https://api.github.com/orgs/octokit/repos"&nbsp; &nbsp; );&nbsp; &nbsp; const result = await response.json();&nbsp; &nbsp; const contri = [];&nbsp; &nbsp; console.log(result);&nbsp; &nbsp; result.forEach((item) => {&nbsp; &nbsp; &nbsp; contri.push(fetch(`${item.contributors_url}`));&nbsp; &nbsp; });&nbsp; &nbsp; Promise.all(contri)&nbsp; &nbsp; &nbsp; .then((contributorResults) => contributorResults)&nbsp; &nbsp; &nbsp; .then((responses) => {&nbsp; &nbsp; &nbsp; &nbsp; console.log(responses);&nbsp; &nbsp; &nbsp; &nbsp; return Promise.all(responses.map((r) => r.json()));&nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; .then((cont) => {&nbsp; &nbsp; &nbsp; &nbsp; setContributor([...cont])&nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; setRepos(result);&nbsp; } catch (err) {&nbsp; &nbsp; console.log(err);&nbsp; } finally {&nbsp; &nbsp; setIsLoading(false);&nbsp; }}caller();&nbsp; }, []);&nbsp; return (<div>&nbsp; {repos.map((repo,index) => (&nbsp; &nbsp; <div key={repo.id}>&nbsp; &nbsp; &nbsp; <h2> Name: {repo.name} </h2>&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp;{&nbsp; contributor[`${index}`] && contributor[`${index}`].slice(0,5).map(item => {&nbsp; &nbsp; &nbsp; &nbsp; return <div key={item.id}>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <div>{item.login}</div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp;})}&nbsp; &nbsp; &nbsp;</div>&nbsp; ))}&nbsp; {isLoading && <div>...loading</div>}</div>&nbsp; );}export default App;
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript