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

标签 react-native use-effect react-navigation-v5 focuslistener

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

相关文章:

react-native - 如何在 native react 中存储 token ?

reactjs - 波纹效果在拐角处泄漏,好像“可按下”按钮具有边框一样

logging - 如何在 React Native 中进行日志记录

reactjs - React hooks useEffect 调用 API 第二次和第一次调用 API 响应也返回

react-native - react 导航-5 : Multiple MaterialTopTabNavigator in the same screen

ios - 使用react-native-share 在 IOS 上将视频分享到 Instagram

reactjs - Prop 更改不会触发 useEffect

javascript - useEffect 之后的异步运行函数

react-native - 将图标添加到抽屉 react-navigation v5

reactjs - 在 react-navigation 5.x 中放置 createSwitchNavigator 以从 react-navigation 4 迁移到 5.x