簡體   English   中英

如何在反應中使用數組獲取數據?

[英]How can I fetch data with an array in react?

我正在嘗試以數組形式獲取申請人的所有數據:

以下是我如何獲取數組的代碼:

const [applicants, setTeamApplications] = useState([]);

  const fetchApplicationData = async () => {
    const res = await axios.get(`/api/v1/invites/team/applications/${teamId}`);

 const items = res.data.map((item) =>
  await axios.get(`/api/v1/profiles/profile/${item.applicant_publicId}`)
);

    // Set state
    setTeamApplications(res.data);
    // Toggle loading state
    setLoadingState(false);
  }; 

在我console.log(applicants)之后

它給了我這個:

[{…}]
0:
applicant_publicId: "La1618912810062"
application_letter: "apply"
id: 3
response: "Waiting on review"

現在我嘗試使用applicant_publicId publicId 再次獲取數據以獲取更多數據:

/api/v1/profiles/profile/${index.applicant_publicId}

我怎樣才能做到這一點?

您不能在.map回調中await ,因為它是同步的,但您可以 map 響應數據對配置文件的請求數組並使用Promise.all來解析所有配置文件。

const [applicants, setTeamApplications] = useState([]);

const fetchApplicationData = async () => {
  // Toggle loading state
  setLoadingState(true);

  try {
    const res = await axios.get(`/api/v1/invites/team/applications/${teamId}`);

    const profileReqs = res.data.map((item) =>
      axios.get(`/api/v1/profiles/profile/${item.applicant_publicId}`)
    );

    const items = await Promise.all(profileReqs);

    // Set state
    setTeamApplications(res.data);
    setProfiles(items);

  } catch (error) {
    // handler any error state?
  } finally {
    // Toggle loading state
    setLoadingState(false);
  }
}; 

暫無
暫無

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

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