React Hook useEffect Error missing dependency

我对 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>

  )

}


慕码人2483693
浏览 199回答 1
1回答

月关宝盒

当你调用 React 时,它表明这是对这个 useEffect Hook 的依赖。useEffectgetRecipes();getRecipes您可以使用效果进行更新:useEffect(() => {&nbsp; &nbsp; 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)因此,您可以更新为:&nbsp; useEffect(() => {&nbsp; &nbsp; const getRecipes = async () => {&nbsp; &nbsp; &nbsp; const response = await fetch(&nbsp; &nbsp; &nbsp; &nbsp; `https://api.edamam.com/search?q=${query}&app_id=${APP_ID}&app_key=${APP_KEY}`&nbsp; &nbsp; &nbsp; );&nbsp; &nbsp; &nbsp; const data = await response.json();&nbsp; &nbsp; &nbsp; setRecipes(data.hits);&nbsp; &nbsp; &nbsp; console.log(data.hits);&nbsp; &nbsp; };&nbsp; &nbsp; getRecipes();&nbsp; }, [query]);这表示在修改时将调用此效果,这意味着 getRecipes 使用 调用 API。queryquery
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript