获取 API 调用被多次发送

新手上路,请多包涵

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

ID 和应用程序密钥已更改。请注意,这是 componentDidUpdate 因为我在状态更改时运行它 - 从而发送一个获取调用

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);
    }

原文由 Kisho 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 663
2 个回答

该请求取决于 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
      })
  }
}

原文由 Kirill Skomarovskiy 发布,翻译遵循 CC BY-SA 4.0 许可协议

如果您想根据正在更新的某些状态进行 api 调用,您应该使用 Redux 或 React context/hooks API。这些库使订阅某些状态更改并执行适当的操作变得容易。理想情况下,您不应该在 componentDidUpdate 中执行类似 fetch 之类的操作,因为每秒可以调用多次

Redux 确实很快并且经过时间验证,但是需要一些时间来设置和维护围绕它的结构。所以在你的情况下,我会看看 useEffect() React hooks 的方法

原文由 Bibipkins 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题