gpt4 book ai didi

react-native - 如何在单一useEffect react native中使用focus和blur listener

转载 作者:行者123 更新时间:2023-12-05 01:30:24 48 4
gpt4 key购买 nike

如您所知,在 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/

48 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com