【问题标题】:How to use focus and blur listener in single useEffect react native如何在单个useEffect中使用焦点和模糊侦听器反应原生
【发布时间】:2021-07-10 03:47:31
【问题描述】:

正如您在 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]);

【问题讨论】:

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


    【解决方案1】:

    你可以这样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

    【讨论】:

      【解决方案2】:

      我没有对此进行测试,但您也许可以这样做:

      useEffect(() => {
          const unsubscribe = navigation.addListener('focus', () => {
              // code
          });
          const unsubscribe2 = navigation.addListener('blur', () => {
              // code
          });
          return () => {
           // executed when unmount
           unsubscribe();
           unsubscribe2();
          }
      }, [navigation]);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-04-12
        • 1970-01-01
        • 1970-01-01
        • 2019-06-14
        • 1970-01-01
        • 2014-03-14
        • 2021-04-05
        相关资源
        最近更新 更多