简体   繁体   English

React Hook useEffect 错误缺少依赖项

[英]React Hook useEffect Error missing dependency

I'm very new to React and I'm trying to build an app, but I'm getting this error: React Hook useEffect has a missing dependency: 'getRecipes'.我对 React 很陌生,我正在尝试构建一个应用程序,但我收到了这个错误:React Hook useEffect has a missing dependency: 'getRecipes'。 Either include it or remove the dependency array.包括它或删除依赖数组。 I cannot figure out how to fix it.我无法弄清楚如何解决它。 Any help would be appreciated?任何帮助,将不胜感激?

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

As your useEffect calls getRecipes();当您的useEffect调用getRecipes(); React is indicating that getRecipes is a dependency on this useEffect Hook. React 表明getRecipes是对这个 useEffect Hook 的依赖。

You could update with Effect with:您可以使用 Effect 更新:

useEffect(() => {
    getRecipes();
}, [query, getRecipes]);

However you will get但是你会得到

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)

So you can update to:因此,您可以更新为:

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

Which indicates this effect will be called, when query is modified, which means getRecipes call the API with query .这表示在修改query时将调用此效果,这意味着 getRecipes 使用query调用 API 。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM