【发布时间】:2020-04-13 11:07:34
【问题描述】:
所以我正在制作一个食谱应用程序并完成了大部分工作。我现在正在寻找集成高级搜索功能,以便用户可以在点击搜索按钮之前过滤他们想要查看的内容。所以现在,与这个问题相关的状态部分看起来像这样
advancedSearchParameters: [
]
在输入一个术语(斯里兰卡)并点击搜索组件中的搜索按钮时,状态中的 advancedSearchParameters 将更新为类似这样的内容
{
balanced: false,
highProtein: false,
highFibre: false,
lowFat: false,
lowCarb: false,
lowSodium: false,
vegan: false,
vegetarian: false,
dairyFree: false,
glutenFree: false,
lowSugar: false,
peanutFree: false,
resultNum: 20,
searchTerm: ''
}
这将提示组件更新
async componentDidUpdate(prevProps, prevState) {
if (
prevState.advancedSearchParameters !== this.advancedSearchParameters &&
this.state.advancedSearchParameters.searchTerm !== ''
) {
let response = await axios.get(
`https://api.edamam.com/search?q=${this.state.advancedSearchParameters
.searchTerm}&app_id=cf7e1&app_key=946d6fb34df02a86bd47b89433&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 });
}
}
当我这样做时出现的问题是 API 调用似乎被发送了多次,提示 API 阻止我的请求至少一分钟。谁能看到我哪里出错了?
【问题讨论】:
-
不要使用
componentDidUpdate来获取异步请求,为什么不使用点击处理程序,我的意思是你传递给你搜索按钮的onClickprop的函数? -
因为这是对外部 API 的调用,据我所知,应该在 componentDidUpdate @rzwnahmd 中调用更改我的状态和呈现新组件的 Api 调用
标签: javascript reactjs api