如何在 Single useEffect React Native 中使用焦点和模糊监听器

Ali*_*man 3 focuslistener react-native use-effect react-navigation-v5

unsubscribe如您所知,在 useEffect 中,如果我们将任何侦听器分配给 const,我们会在最后返回 ,unsubscribe如下所示

当我们使用

useEffect(() => {
    const unsubscribe = navigation.addListener('focus', () => {
        // code
    })
    return unsubscribe;

}, [navigation]);
Run Code Online (Sandbox Code Playgroud)

如我所愿

useEffect(() => {
    const unsubscribe = navigation.addListener('focus', () => {
        // code
    })
    const unsubscribe2 = navigation.addListener('blur', () => {
        // code
    })

    // need to return both listeners

}, [navigation]);
Run Code Online (Sandbox Code Playgroud)

Som*_*ial 5

你可以cleanup喜欢这个

useEffect(() => {

    navigation.addListener('focus', handler)
    navigation.addListener('blur', handler)
    return () => {
                navigation.removeListener('focus', handler)
                navigation.removeListener('blur', handler)
            }

},[navigation])
Run Code Online (Sandbox Code Playgroud)

官方示例在这里https://reactjs.org/docs/hooks-effect.html#effects-with-cleanup