如何在单一useEffect react native中使用focus和blur listener
How to use focus and blur listener in single useEffect react native
如您所知,在 useEffect 中我们 return 最后的 unsubscribe
如果我们将任何侦听器分配给 unsubscribe
常量,如下所示
我们正在使用
useEffect(() => {
const unsubscribe = navigation.addListener('focus', () => {
// code
})
return unsubscribe;
}, [navigation]);
如我所愿
useEffect(() => {
const unsubscribe = navigation.addListener('focus', () => {
// code
})
const unsubscribe2 = navigation.addListener('blur', () => {
// code
})
// need to return both listeners
}, [navigation]);
你可以cleanup
这样
useEffect(() => {
navigation.addListener('focus', handler)
navigation.addListener('blur', handler)
return () => {
navigation.removeListener('focus', handler)
navigation.removeListener('blur', handler)
}
},[navigation])
这里是官方例子https://reactjs.org/docs/hooks-effect.html#effects-with-cleanup
我没有对此进行测试,但您可以这样做:
useEffect(() => {
const unsubscribe = navigation.addListener('focus', () => {
// code
});
const unsubscribe2 = navigation.addListener('blur', () => {
// code
});
return () => {
// executed when unmount
unsubscribe();
unsubscribe2();
}
}, [navigation]);
如您所知,在 useEffect 中我们 return 最后的 unsubscribe
如果我们将任何侦听器分配给 unsubscribe
常量,如下所示
我们正在使用
useEffect(() => {
const unsubscribe = navigation.addListener('focus', () => {
// code
})
return unsubscribe;
}, [navigation]);
如我所愿
useEffect(() => {
const unsubscribe = navigation.addListener('focus', () => {
// code
})
const unsubscribe2 = navigation.addListener('blur', () => {
// code
})
// need to return both listeners
}, [navigation]);
你可以cleanup
这样
useEffect(() => {
navigation.addListener('focus', handler)
navigation.addListener('blur', handler)
return () => {
navigation.removeListener('focus', handler)
navigation.removeListener('blur', handler)
}
},[navigation])
这里是官方例子https://reactjs.org/docs/hooks-effect.html#effects-with-cleanup
我没有对此进行测试,但您可以这样做:
useEffect(() => {
const unsubscribe = navigation.addListener('focus', () => {
// code
});
const unsubscribe2 = navigation.addListener('blur', () => {
// code
});
return () => {
// executed when unmount
unsubscribe();
unsubscribe2();
}
}, [navigation]);