如何提前退出useEffect hook?
How to early exit useEffect hook?
在docs中它说我们应该只在组件的顶层调用钩子。由于 useEffect 的 API,return
已经保留用于清理,这让我想知道如何提前退出 useEffect 挂钩以防止深度嵌套我的 if 语句。
// instead of
React.useEffect(() => {
if (foo){
// do something
}
})
// I would rather write something like
React.useEffect(() => {
if (!foo){
// exit early and stop executing the rest of the useEffect hook
}
// do something
})
我怎样才能做到这一点?在我的第一个示例中,复杂的条件逻辑很快就会变得混乱,尤其是考虑到我不能在条件语句中使用 useEffect
。
与任何函数一样,可以使用 return
关键字提前退出。
这两个片段是等价的:
React.useEffect(() => {
if (foo){
// do something
}
})
React.useEffect(() => {
if (!foo){
return;
}
// do something
})
在docs中它说我们应该只在组件的顶层调用钩子。由于 useEffect 的 API,return
已经保留用于清理,这让我想知道如何提前退出 useEffect 挂钩以防止深度嵌套我的 if 语句。
// instead of
React.useEffect(() => {
if (foo){
// do something
}
})
// I would rather write something like
React.useEffect(() => {
if (!foo){
// exit early and stop executing the rest of the useEffect hook
}
// do something
})
我怎样才能做到这一点?在我的第一个示例中,复杂的条件逻辑很快就会变得混乱,尤其是考虑到我不能在条件语句中使用 useEffect
。
与任何函数一样,可以使用 return
关键字提前退出。
这两个片段是等价的:
React.useEffect(() => {
if (foo){
// do something
}
})
React.useEffect(() => {
if (!foo){
return;
}
// do something
})