[英]useEffect and 'react-hooks/exhaustive-deps' linting
I included an empty array because this should only run once, however I'm getting the linting warning because I'm not including ajaxCallsInProgress
as a dependency.我包含了一个空数组,因为它应该只运行一次,但是我收到了 linting 警告,因为我没有将
ajaxCallsInProgress
作为依赖项包含在内。 The reason I don't is that it creates an infinite loop if I do.我不这样做的原因是,如果我这样做,它会创建一个无限循环。 Is there a better way to handle this scenario that will eliminate the linting warning?
有没有更好的方法来处理这种情况,以消除掉毛警告? This is pretty straight-forward and a valid scenario as far as I can tell.
据我所知,这是非常直接且有效的场景。
useEffect(() => {
const fetch = async () => {
// update state to show pending
setAjaxCallsInProgress(ajaxCallsInProgress + 1)
try {
const humans = await getHumans()
setHumans(humans)
} catch (error) {
setError(error)
} finally {
setAjaxCallsInProgress(ajaxCallsInProgress - 1)
}
}
fetch()
}, [])
In-/decrementing the state doesn't require you to know the current state because setState
has a callback version that receives the current state as an argument and returns the next state:在-/递减状态不需要你知道当前状态,因为
setState
有一个回调版本,它接收当前状态作为参数并返回下一个状态:
const [ajaxCallsInProgress, setAjaxCallsInProgress] = useState(0);
useEffect(() => {
const fetch = async () => {
// update state to show pending
setAjaxCallsInProgress(current => current + 1)
try {
const humans = await getHumans()
setHumans(humans)
} catch (error) {
setError(error)
} finally {
setAjaxCallsInProgress(current => current - 1)
}
}
fetch()
}, [])
This will remove the dependency on ajaxCallsInProgress
and is also a best practice for updating state based on the current state:这将消除对
ajaxCallsInProgress
的依赖,也是基于当前状态更新状态的最佳实践:
How do I update state with values that depend on the current state?
如何使用取决于当前状态的值更新状态?
Pass a function instead of an object to
setState
to ensure the call always uses the most updated version of state (see below).将函数而不是对象传递给
setState
以确保调用始终使用最新版本的状态(见下文)。
You should generally use it when accessing the current state to update the state.您通常应该在访问当前状态时使用它来更新状态。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.