如您所知,在 useEffect 中,如果我们将任何监听器分配给 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]);
最佳答案
你可以像这样清理
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
关于react-native - 如何在单一useEffect react native中使用focus和blur listener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67102832/