我正在构建一个食谱应用程序,由于某种原因,我的 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 许可协议
该请求取决于
this.state.searchTerm
。因此,如果更改了this.state.searchTerm
,您的组件将发出请求。