【问题标题】:React Hook useEffect Error missing dependencyReact Hook useEffect 错误缺少依赖项
【发布时间】:2020-05-20 20:54:15
【问题描述】:

我是 React 的新手,我正在尝试构建一个应用程序,但我收到了这个错误:React Hook useEffect has a missing dependency: '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>
  )
}

【问题讨论】:

    标签: javascript reactjs error-handling react-hooks


    【解决方案1】:

    当您的 useEffect 调用 getRecipes(); 时,React 表明 getRecipes 是此 useEffect Hook 的依赖项。

    你可以用 Effect 更新:

    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。

    【讨论】:

    • 你能记住这个函数,让它永远不会改变,也不需要成为依赖项吗?因为没有它,这可能意味着useEffect 被调用了太多次。
    • 如何记忆函数?我对这一切都很陌生
    • 是的,正是这样做的,将 getRecipes 移动到 useEffect 中。非常感谢您的帮助
    猜你喜欢
    • 2021-02-23
    • 2019-10-24
    • 2020-10-26
    • 2020-03-07
    • 2020-02-25
    • 2020-06-11
    • 2020-03-30
    • 2020-12-29
    • 2019-09-20
    相关资源
    最近更新 更多