繁体   English   中英

fetch API 调用被多次发送

[英]fetch API call being sent multiple times

我正在构建一个食谱应用程序,由于某种原因,我的 API 调用被发送了 5 次,因为我在 console.log 中看到了 5 次数据。 这对我来说是个问题,因为 API 阻止我每分钟发送超过 5 个呼叫,如果最终产品有同样的问题,它不会对用户体验非常友好。 谁能在下面的代码中看到我哪里出错了?

Id 和应用程序密钥已更改。 请注意,这是 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);
    }

该请求取决于this.state.searchTerm 因此,如果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
      })
  }
}

问题是您正在组件的componentDidUpdate方法中获取数据并使用setState 它触发组件重新渲染,并且您的componentDidUpdate中的代码在每个setState之后一次又一次地执行。 使用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. 这些库可以轻松订阅一些 state 更改并执行适当的操作。 理想情况下,您不应在componentDidUpdate中执行类似 fetch 之类的操作,因为它每秒可以调用多次
Redux 速度非常快且经过时间验证,但需要一些时间来设置和维护它周围的结构。 所以在你的情况下,我会看看 React 钩子的useEffect()方法

由于原始问题已更新,因此我的答案不再相关(已发布正确答案)。 所以,我正在删除它。

暂无
暂无

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

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