【问题标题】:How to unsubscribe from an array of subscription如何取消订阅数组
【发布时间】:2020-07-18 01:52:21
【问题描述】:

我有一个来自 Apollo 查询的 subscribeToMore 数组,我想使用它。我受到这个article 的启发,希望我想使用一个函数式组件:

useEffect(() => {
    const unsubscribe =
        [subscribeToMore({
            // subscriptionData...
        }), subscribeToMore({
            // subscriptionData...
        })]


    if (unsubscribe.length > 0) {
        for (i = 0; i < unsubscribe.length; i++) {
            return () => unsubscribe[i]()
        }
    }
}, [subscribeToMore])

但是,我得到:

在 unsubscribe[i]() 中,unsubscribe[i] 是未定义的

【问题讨论】:

    标签: javascript reactjs react-native react-apollo


    【解决方案1】:

    useEffect 只有一个返回函数。你不能多次调用它。相反,在返回函数中,您可以检查条件并取消订阅,如果有要清除的订阅

    useEffect(() => {
        const unsubscribe =
            [subscribeToMore({
                // subscriptionData...
            }), subscribeToMore({
                // subscriptionData...
            })]
    
        return () => {
           if (unsubscribe.length > 0) {
               for (i = 0; i < unsubscribe.length; i++) {
                   unsubscribe[i]()
               }
           }
        }
    
    }, [subscribeToMore])
    

    【讨论】:

      猜你喜欢
      • 2022-01-19
      • 2012-03-14
      • 2019-12-05
      • 1970-01-01
      • 1970-01-01
      • 2015-08-24
      • 1970-01-01
      • 2015-08-11
      • 1970-01-01
      相关资源
      最近更新 更多