我是React的新手,我正在尝试构建一个应用程序,但是我收到此错误:React Hook useEffect缺少依赖项:"getRecipes"。要么包含它,要么删除依赖项数组。我不知道如何解决它。 任何帮助将不胜感激?
useEffect( () => {
getRecipes();
}, [query]);
const getRecipes = async () => {
const response = await fetch(`https://api.edamam.com/search?q=${query}&app_id=${APP_ID}&app_key=${APP_KEY}`);
const data = await response.json();
setRecipes(data.hits);
console.log(data.hits);
}
const updateSearch = e => {
setSearch(e.target.value);
}
const getSearch = e => {
e.preventDefault();
setQuery(search)
}
return(
<div className="App">
<form onSubmit={getSearch}className="container">
<input className="mt-4 form-control" type="text" value={search} onChange={updateSearch}/>
<button className="mt-4 mb-4 btn btn-primary form-control" type="submit">Search</button>
</form>
<div className="recipes">
{recipes.map(recipe => (
<Recipe
key={recipe.label}
title={recipe.recipe.label} image={recipe.recipe.image}
ingredients={recipe.recipe.ingredients}calories={recipe.recipe.calories}
/>
))}
</div>
</div>
)
}
正如你的useEffect
所调用的那样getRecipes();
React表明getRecipes
依赖于这个useEffect Hook。
您可以使用以下方法使用效果进行更新:
useEffect(() => {
getRecipes();
}, [query, getRecipes]);
但是你会得到
The 'getRecipes' function makes the dependencies of useEffect Hook (at line 18) change on every render. Move it inside the useEffect callback. Alternatively, wrap the 'getRecipes' definition into its own useCallback() Hook. (react-hooks/exhaustive-deps)
因此,您可以更新到:
useEffect(() => {
const getRecipes = async () => {
const response = await fetch(
`https://api.edamam.com/search?q=${query}&app_id=${APP_ID}&app_key=${APP_KEY}`
);
const data = await response.json();
setRecipes(data.hits);
console.log(data.hits);
};
getRecipes();
}, [query]);
这表明当修改query
时将调用此效果,这意味着getRerecies使用query
调用API。