React Hook useEffect错误缺少依赖项

时间:2020-05-20 20:54:15

标签: javascript reactjs error-handling react-hooks

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

1 个答案:

答案 0 :(得分:0)

当您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。