简体   繁体   English

无法从 API 使用 foreach 循环和 Fetch API 获取多个数据获取请求

[英]Can't get multiple data from API using foreach loop with Fetch API get request

In my project, I need to get organization data's from api firstly, then ı need to get another specific data's from another api with sending as a parameter organizationEIC property of my organization data which ı get in first request.在我的项目中,我需要首先从 api 获取组织数据,然后我需要从另一个 api 获取另一个特定数据,并作为参数发送我的组织数据的组织EIC 属性,我在第一个请求中获得。 I can get the organization datas successfully and set them to items state successfully.我可以成功获取组织数据并将它们成功设置为项目 state。 But when ı came to the second API request which made in getPlants() method, my program and my RAM fail and ı get net::ERR_INSUFFICIENT_RESOURCES error for each request.但是当我遇到在 getPlants() 方法中发出的第二个 API 请求时,我的程序和我的 RAM 失败,并且每个请求都会出现net::ERR_INSUFFICIENT_RESOURCES错误。 I just put the incoming data to the datas array in order not to setState every time and to prevent the component from rendering again, but the program still crashes.我只是将传入的数据放入datas数组中,以免每次都setState并防止组件再次渲染,但程序仍然崩溃。 I got some solutions with using hooks but I'm beginner in react and ı don't have any knowledge about hooks and want to solve this issue with basic react to develop myself better.我得到了一些使用钩子的解决方案,但我是反应的初学者,我对钩子没有任何了解,想用基本的反应来解决这个问题,以更好地发展自己。

state = {
    items: [],

    plants: []
  } 

componentDidMount() {
    fetch('https://cors-anywhere.herokuapp.com/https://seffaflik.epias.com.tr/transparency/service/production/dpp-organization', {
      method: "GET",
      headers: {
        "Content-Type": "application/json",
        'X-Requested-With': 'XMLHttpRequest'
      }
    })
      .then(response =>
        response.json())
      .then(resultJson => {
        this.setState({
          items: resultJson.body.organizations,      //can get successfully and set state items ok.
        })
        
      });
  }

getPlants = () =>{
    this.state.items.forEach((plant) => {            //foreach loop with using items state
      fetch(`https://cors-anywhere.herokuapp.com/https://seffaflik.epias.com.tr/transparency/service/production/dpp-injection-unit-name?organizationEIC=${plant.organizationETSOCode}`, {
        method: 'GET',
        headers: {
          "Content-Type": "application/json",
          'X-Requested-With': 'XMLHttpRequest'
        }
      })
        .then(response => response.json())
        .then(resultJson => {
          datas.push(resultJson.body.injectionUnitNames)     //where ı fail
        })
    })
  }

  render() {
    this.getPlants()           //just necessery part of render method
    console.log(datas)

THX in advance for your help and suggestions提前 THX 为您提供帮助和建议

(1) This probably happened because you are calling.getPlants() on every render. (1) 这可能是因为您在每次渲染时都调用了.getPlants()。 You should probably call getPlants inside componentDidMount instead.您应该改为在 componentDidMount 中调用getPlants

(2) You may use promise.all to speed up your fetch. (2) 您可以使用 promise.all 来加快您的抓取速度。

getPlants = async (items) =>{

const data = await Promise.all( items.map((plant) => {
     return fetch(`https://cors-anywhere.herokuapp.com/https://seffaflik.epias.com.tr/transparency/service/production/dpp-injection-unit-name?organizationEIC=${plant.organizationETSOCode}`, {
    method: 'GET',
    headers: {
      "Content-Type": "application/json",
      'X-Requested-With': 'XMLHttpRequest'
    }
  }).then(response => response.json())
}))

this.setState({ data })
}

ComponentDidMount ComponentDidMount

componentDidMount() {
    fetch('https://cors-anywhere.herokuapp.com/https://seffaflik.epias.com.tr/transparency/service/production/dpp-organization', {
      method: "GET",
      headers: {
        "Content-Type": "application/json",
        'X-Requested-With': 'XMLHttpRequest'
      }
    })
      .then(response =>
        response.json())
      .then(async resultJson => {
        this.setState({
          items: resultJson.body.organizations,      //can get successfully and set state items ok.
        })
        await getPlants(resultJson.body.organizations) // we call get plants here
        
      });
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM