React与Axios中的嵌套API调用

yiytaume  于 2023-11-18  发布在  iOS
关注(0)|答案(1)|浏览(124)

我已经搜索了很多论坛和文章,但仍然没有得到这段代码的工作。我能够注销正确的数据,但由于某种原因,当我试图设置状态,我得到一个空对象。我已经在这几个小时了,所以很可能我错过了一些简单的东西。
在下面的代码块中,console.log(tempOwnership)按照它应该的方式工作(字典对象数组),但是setOwnerData(tempOwnership)似乎没有正确的效果,因为没有任何东西呈现给DOM。如果我注解掉这行“mechanical”呈现,因为这是默认的State。

import './index.css'
import axios from 'axios'
import {useParams} from 'react-router-dom';
import { DTSummaryAPI, OwnershipAPI, OwnershipDomainAPI, UserAPI } from 'src/apis/designtrack';
import { useEffect, useState } from 'react';

function DTSummary() {
  let {id} = useParams();
  
  const [summaryData, setSummaryData] = useState("Loading");
  const [ownerData, setOwnerData] = useState([{"domain": "mechanical"}]);

  useEffect(() => {
    fetchOwnershipData(id)
    fetchSummaryData(id)
  }, [])

  const fetchSummaryData = async (id) => {
    try{
      const response = await DTSummaryAPI.getById(id)
      setSummaryData(response.data)
    } catch (error) {
      console.log(error);
    }
  }

  const fetchOwnershipData = async (id) => {
    let tempOwnership = []
    try {
      const results = await OwnershipAPI.getByDt(id)
      results.data.forEach(element => {
        fetchOwnerData(element.domain, element.user)
        .then(data => {
          tempOwnership.push(data);
        }).catch(error => {console.log(error);});
      })
    } catch (error) {
      console.log(error);
    }
    console.log(tempOwnership)
    setOwnerData(tempOwnership)
  } 

  const fetchOwnerData = async(domainId, userId) => {
    let ownership = {}
    await axios.all(
      [
        OwnershipDomainAPI.getById(domainId),
        UserAPI.getById(userId)
      ]).then(axios.spread((domain, user) => {
        ownership["domain"] = domain.data.name
        ownership["username"] = userId
        ownership["firstname"] = user.data.firstname
        ownership["lastname"] = user.data.surname
      })).catch(error => {console.log(error)})
      return ownership
  }
  

  return (
    <div className="container-fluid">
      <div className="row">
        <div className="col-8">
          <h1>{summaryData.title}</h1>
          <div>
            {ownerData.map((items, index) => {
              return <p key={index}>{items.domain}</p>
            })}
          </div>
        </div>
        <div className="col-4">
          <h1>Thumbnail</h1>
        </div>
      </div>
      
    </div>
  );
}

export default DTSummary;

字符串

vuktfyat

vuktfyat1#

用标准for循环替换forEach循环,fetchOwnerData调用现在直接在循环中等待,以确保正确的异步行为。

const fetchOwnershipData = async (id) => {
  let tempOwnership = [];
  try {
    const results = await OwnershipAPI.getByDt(id);
    for (let i = 0; i < results.data.length; i++) {
      const element = results.data[i];
      try {
        const data = await fetchOwnerData(element.domain, element.user);
        tempOwnership.push(data);
      } catch (error) {
        console.log(error);
      }
    }
  } catch (error) {
    console.log(error);
  }
  console.log(tempOwnership);
  setOwnerData(tempOwnership);
};

字符串

相关问题