微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在单次使用中使用焦点和模糊监听器效果反应原生

如何解决如何在单次使用中使用焦点和模糊监听器效果反应原生

正如你在 useEffect 中所知道的,如果我们将任何侦听器分配给 unsubscribe const,我们会在最后返回 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]);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。