【问题标题】:React Hook useEffect has a missing dependency: 'fetchProfile'. Either include it or remove the dependency array react-hooks/exhaustive-depsReact Hook useEffect 缺少依赖项:'fetchProfile'。要么包含它,要么移除依赖数组 react-hooks/exhaustive-deps
【发布时间】:2020-06-09 21:37:09
【问题描述】:

我收到此警告,我想知道需要采取哪些步骤才能从控制台中删除警告。问题是,我在其他地方使用了 fetchProfile() 函数,所以我不能在 useEffect 中移动它。有什么建议?我的代码如下:

  const fetchProfile = async () => {
    const token = await localStorage.FBIdToken
    await axios
      .get(`/user`, {
        headers: {
          Authorization: `${token}`
        }
      })
      .then(res => {
        setUser(res.data)
        setFormData({
          ...formData,
          github: res.data.user.github ? res.data.user.github : '',
          website: res.data.user.website ? res.data.user.website : '',
          linkedIn: res.data.user.linkedIn ? res.data.user.linkedIn : '',
          cohort: res.data.user.cohort,
          program: res.data.user.program
        })
      })
      .catch(err => console.log('error'))
  }

  useEffect(() => {
    fetchProfile()
  }, [])

【问题讨论】:

  • 将获取配置文件添加到依赖数组中也不会删除警告
  • 您的fetchProfile 函数是否定义在组件中?
  • 是的,我的获取配置文件已在组件中定义

标签: reactjs


【解决方案1】:

将函数包装在useCallback 中并将其添加为依赖项应该可以工作,如下所示:

const fetchProfile = useCallback(async () => {
  // Do request as per normal
}, [])

useEffect(fetchProfile, [fetchProfile])

另一种选择是将fetchProfile 函数移出 组件并将setter 传递给调用:

// This is defined outside your component
const fetchProfile = async ({ setUser, setFormData }) => {
  // Do request as per normal
}

useEffect(() => {
  fetchProfile({ setUser, setFormData })
}, [])

【讨论】:

    【解决方案2】:

    您收到警告是因为您在钩子中使用了fetchProfile,但未将其包含在依赖项中。如果fetchProfile 更改,您的效果将不会运行。

    要消除警告,请将fetchProfile 添加到依赖项(useEffect() 的第二个参数):

    useEffect(() => {
      fetchProfile()
    }, [fetchProfile])
    

    【讨论】:

      猜你喜欢
      • 2021-10-31
      • 2020-06-18
      • 2021-10-21
      • 2021-07-15
      • 2021-12-06
      • 1970-01-01
      • 1970-01-01
      • 2023-01-15
      • 2022-01-09
      相关资源
      最近更新 更多