gpt4 book ai didi

javascript - React Hook useEffect错误缺少依赖项

转载 作者:行者123 更新时间:2023-12-03 08:40:31 25 4
gpt4 key购买 nike

我对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时将调用此效果,这意味着getRecipes使用 query调用API。

关于javascript - React Hook useEffect错误缺少依赖项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61922703/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com