如何取消订阅数组

subscribeToMore我有一个我想使用的来自 Apollo 的查询数组。我受到这篇文章的启发,希望我想使用一个功能组件:


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] 是未定义的


Helenr
浏览 100回答 1
1回答

ABOUTYOU

useEffect只有一个返回函数。你不能多次调用它。相反,在 return 函数中,您可以检查条件并取消订阅是否有要清除的订阅useEffect(() => {&nbsp; &nbsp; const unsubscribe =&nbsp; &nbsp; &nbsp; &nbsp; [subscribeToMore({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // subscriptionData...&nbsp; &nbsp; &nbsp; &nbsp; }), subscribeToMore({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // subscriptionData...&nbsp; &nbsp; &nbsp; &nbsp; })]&nbsp; &nbsp; return () => {&nbsp; &nbsp; &nbsp; &nbsp;if (unsubscribe.length > 0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;for (i = 0; i < unsubscribe.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;unsubscribe[i]()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; }}, [subscribeToMore])
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript