Javascript 我可以使用两个useEffect并在地图中添加地图吗

Javascript 我可以使用两个useEffect并在地图中添加地图吗,javascript,reactjs,react-hooks,Javascript,Reactjs,React Hooks,我是新的反应,并希望一些帮助与以下问题。我有这个密码 import React, { useState, useEffect } from "react"; function FetchData() { const [repos, setRepos] = useState([]); const [isLoading, setIsLoading] = useState(true); useEffect(() => { fetch("ht

我是新的反应,并希望一些帮助与以下问题。我有这个密码

 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>
))}

您可以在一个useEffect内直接调用API

import React,{useState,useffect}来自“React”;
函数App(){
常量[repos,setRepos]=useState([]);
const[contributor,setContributor]=useState([]);
const[isLoading,setIsLoading]=useState(true);
useffect(()=>{
异步函数调用程序(){
试一试{
设置加载(真);
const response=等待获取(
"https://api.github.com/orgs/octokit/repos"
);
const result=wait response.json();
常量contri=[];
控制台日志(结果);
结果.forEach((项目)=>{
contri.push(fetch(`${item.contributors\u url}');
});
承诺。全部(contri)
.然后((贡献者结果)=>贡献者结果)
。然后((回答)=>{
控制台日志(响应);
返回Promise.all(responses.map((r)=>r.json());
})
。然后((续)=>{
setContributor([…cont])
});
setRepos(结果);
}捕捉(错误){
控制台日志(err);
}最后{
设置加载(假);
}
}
调用者();
}, []);
返回(
{repos.map((repo,index)=>(
名称:{repo.Name}
{contributor[`${index}`]和&contributor[`${index}`].slice(0,5).map(项=>{
返回
{item.login}
})}
))}
{isLoading&&…loading}
);
}

导出默认应用程序,因为您是新的反应者。React过去使用基于类的组件来处理状态,这些基于类的组件具有称为-生命周期方法的特殊功能。但是从React 16.8开始,React社区提出了React挂钩,功能组件现在可以用来处理状态,useState()和useEffect()就是挂钩的例子

现在,useffect()单独用于执行生命周期方法的工作

您在代码中使用useffect()的方式是模拟componentDidMount(),因为您将第二个参数保留为空数组[]

我们可以使用其他生命周期方法,如componentdiddupdate()componetnWillUnmount()使用useffect()钩子本身

然后根据您的需求,您可以根据组件的需要多次使用useffect()钩子。

现在进入问题的更新部分:

因此,您基本上需要做承诺链接。我们知道fetch()是基于承诺的,因此当一个异步调用被解析并且我们获得第一个数据时,仅在useffect()钩子中,您需要使用第二个url端点发出另一个异步请求以获得相应的数据

这是现在更新的代码:试试这个

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>
  );
}
import React,{useState,useffect}来自“React”;
函数FetchData(){
常量[repos,setRepos]=useState([]);
const[isLoading,setIsLoading]=useState(true);
const[contributors,setContributors]=useState([]);
常量[isContributorLoading,setIsContributorLoading]=使用状态(true);
useffect(()=>{
取('https://api.github.com/orgs/{org}/repos')
.然后((res)=>res.json())
。然后((数据)=>{
setRepos(数据);//接收到数据1(repos)
//现在我们进行另一个API调用以获取数据2(贡献者)
返回获取('https://api.github.com/repos/{org}/{repos}/contributors');
})
.then((res)=>res.json())//链接承诺,处理第二次获取请求
。然后((数据2)=>{
console.log(data2);
setContributors(数据2);
})
.然后(()=>{
设置加载(假);
})
.catch((err)=>console.log(err));
}, []);
返回(
{repos.length&&repos.map((repo)=>(
名称:{repo.Name}
))}
前5名贡献者:

    {contributors.length&&contributors.map((c,i)=>{ 返回
  • {c.name}
  • )}
); }

因此,基本上您需要学习更多关于如何使用钩子的知识,尤其是useffect(),现在。做一些谷歌搜索,如果我现在告诉你一切就不好了。那么试一试。

如果它是一个单独的API请求和一组单独的数据,那么是的,你可以对它有一个不同的状态值和效果谢谢你的答案,但是要得到
https://api.github.com/repos/{org}/{repos}/贡献者
我首先必须从第一个获取请求获取
警告不要使用
async
?@KhooWingHang-您想为每个repo获取前5名contibutor,因为第一次调用将为您提供所有存储库?@dcangulo-没有警告使用async。您不应该在useffect中以这种方式使用async。您必须从useffect中调用/创建一个async函数。请查看此处的参考rence:@Lashan Fernando:我已经批准了您的编辑。请继续。不过我还是像以前一样故意保留代码,因为我们不知道Khoo Wing Hang想如何实现它。:)不管怎么说,编辑得好,留着吧up@KhooWing Hang:你的问题解决了吗,兄弟,如果不让我知道你真正想要达到的目标,我一定会帮你完成:)我添加了我想做的编辑。希望它有意义。@KhooWingHang已经根据你的要求为你更新了答案,并谈了一些概念这可以帮助您成为一名更好的开发人员。如果您还有任何疑问,请联系我们的联系人。:)编码愉快,如果我以任何形式帮助过您,请接受我的回答。这促使我帮助越来越多的编码人员。谢谢
https://api.github.com/repos/{org}/{repos}/contributorsimport 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>
  );
}