[英]React Hook useEffect has a missing dependency: 'fetchProfile'. Either include it or remove the dependency array react-hooks/exhaustive-deps
I am getting this warning and I was wondering what steps I need to take to remove the warning from my console.我收到此警告,我想知道需要采取哪些步骤才能从控制台中删除警告。 The issue being, I am using the fetchProfile() function elsewhere so I can't move it within the useEffect.
问题是,我在别处使用了 fetchProfile() 函数,所以我无法在 useEffect 中移动它。 any suggestions?
有什么建议? My code is as follows:
我的代码如下:
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()
}, [])
Wrapping the function in useCallback
and adding it as a dependency should work, like so:将函数包装在
useCallback
并将其添加为依赖项应该可以工作,如下所示:
const fetchProfile = useCallback(async () => {
// Do request as per normal
}, [])
useEffect(fetchProfile, [fetchProfile])
Another option is to move the fetchProfile
function outside the component and pass in the setters to the call:另一种选择是将
fetchProfile
函数移到组件外,并将 setter 传递给调用:
// This is defined outside your component
const fetchProfile = async ({ setUser, setFormData }) => {
// Do request as per normal
}
useEffect(() => {
fetchProfile({ setUser, setFormData })
}, [])
You're getting the warning because you're using fetchProfile
inside your hook, but not including it in the dependencies.您收到警告是因为您在钩子中使用了
fetchProfile
,但未将其包含在依赖项中。 If fetchProfile
changes, your effect won't run.如果
fetchProfile
更改,您的效果将不会运行。
To get rid of the warning, add fetchProfile
to the dependencies (the second argument to useEffect()
):要消除警告,请将
fetchProfile
添加到依赖项( useEffect()
的第二个参数):
useEffect(() => {
fetchProfile()
}, [fetchProfile])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.