简体   繁体   English

fetch API 调用被多次发送

[英]fetch API call being sent multiple times

I am building a recipe app and for some reason my API calls are sent 5 times since I see the data 5 times when in console.log it.我正在构建一个食谱应用程序,由于某种原因,我的 API 调用被发送了 5 次,因为我在 console.log 中看到了 5 次数据。 This is an issue for me as the API blocks me from sending more than 5 calls a minute and it wont be very UX friendly if the end product has the same issue.这对我来说是个问题,因为 API 阻止我每分钟发送超过 5 个呼叫,如果最终产品有同样的问题,它不会对用户体验非常友好。 Can anyone see where I am going wrong in the below code?谁能在下面的代码中看到我哪里出错了?

Id and app key is changed. Id 和应用程序密钥已更改。 please note that this is componentDidUpdate since I am running it when the state is changed -thus sending a fetch call请注意,这是 componentDidUpdate,因为当 state 更改时我正在运行它 - 从而发送 fetch 调用

async componentDidUpdate() {
        let response = await axios.get(
            `https://api.edamam.com/search?q=${this.state
                .searchTerm}&app_id=c5e1&app_key=946ddb0f02a86bd47b89433&to=20`
        );
        let data = response.data.hits.map((data) => ({
            name: data.recipe.label,
            src: data.recipe.image,
            source: data.recipe.source,
            url: data.recipe.url,
            healthLabels: data.recipe.healthLabels,
            dietLabels: data.recipe.dietLabels,
            calories: data.recipe.calories,
            totalWeight: data.recipe.totalWeight,
            totalTime: data.recipe.totalTime,
            totalNutrients: data.recipe.totalNutrients,
            ingredients: data.recipe.ingredients
        }));
        this.setState({ recipeResults: data });
        console.log(data);
    }

The request depends on this.state.searchTerm .该请求取决于this.state.searchTerm so if this.state.searchTerm is changed your component will make a request.因此,如果this.state.searchTerm发生更改,您的组件将发出请求。

componentDidUpdate(prevProps, prevState) {
  if (prevState.searchTerm !== this.state.searchTerm) {
    axios.get(`https://api.edamam.com/search?q=${this.state.searchTerm}&app_id=c5e1&app_key=946ddb0f02a86bd47b89433&to=20`)
      .then((response) => {
        // process response
      })
      .catch(() => {
        // process error
      })
  }
}

The problem is that you are fetching data in componentDidUpdate method of the component and using setState .问题是您正在组件的componentDidUpdate方法中获取数据并使用setState It triggers component re-render and the code inside your componentDidUpdate executes again and again after every setState .它触发组件重新渲染,并且您的componentDidUpdate中的代码在每个setState之后一次又一次地执行。 Use componentDidMount for one time data fetching使用componentDidMount进行一次数据获取

If you want to do api call based on some piece of state being updated you should use either Redux or React context/hooks API. If you want to do api call based on some piece of state being updated you should use either Redux or React context/hooks API. These libraries make it easy to subscribe to some state changes and execute an appropriate action.这些库可以轻松订阅一些 state 更改并执行适当的操作。 Ideally you should not do something like fetch in your componentDidUpdate as it can be called many times per second理想情况下,您不应在componentDidUpdate中执行类似 fetch 之类的操作,因为它每秒可以调用多次
Redux is really fast and time proven but it takes some time to setup and maintain the structure around it. Redux 速度非常快且经过时间验证,但需要一些时间来设置和维护它周围的结构。 So in your case I would look at useEffect() method of React hooks所以在你的情况下,我会看看 React 钩子的useEffect()方法

Since original question has been updated, my answer isn't relevant anymore (there is correct answer already posted).由于原始问题已更新,因此我的答案不再相关(已发布正确答案)。 So, I am removing it.所以,我正在删除它。

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

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