【问题标题】:Nextjs Listener with callback executes itself带有回调的 Nextjs 侦听器自行执行
【发布时间】:2021-08-22 05:34:44
【问题描述】:

我一直在为我的 nextjs 应用程序开发实时通知系统。它工作得很好,我在每一页都这样称呼它:


export default function Bot({user}) {

    startNotifications(user)
}

函数本身是这样的

    const userID = getUserID(user)
    const pubnub = new PubNub({
        subscribeKey: subKey,
        uuid: userID
    });

    const { asPath } = useRouter()
    pubnub.unsubscribeAll();
    pubnub.addListener({
        signal: function(signal) {
            const message = signal.message
            if (message[0] == "bot") {
                Notiflix.Notify.Info(notificationMessage);

                if (check if url is correct here) {
                    callback()
                    return
                }

            }

        }
    })

    pubnub.subscribe({
        channels: ["announcements", userID.toString()],
    });

但是当我尝试添加一个回调函数来改变状态时,取决于这样的通知:

export default function Bot({user}) {

    startNotifications(user, changeState)


    const [value, setValue] = useState(true)

    function changeState(){
      console.log("changing state")
  
      setValue(false)
    }
}

代码运行良好,并且状态正在发生变化,但由于某种原因,代码会自行循环,并使每个通知的侦听器数量增加一倍。在 startNotifications 函数中,我什至尝试取消订阅和重新订阅,但这也不起作用。看起来像这样 (第一次通知)

然后如果我再做几次 4. 通知看起来像这样:

我几乎快要结束了。我曾尝试在同一个文件中实现 startNotifications,但效果相同。

如果有人对此有解决方案(这可能是我不知道的非常明显的事情),请告诉我。祝你有美好的一天。

【问题讨论】:

    标签: reactjs notifications next.js pubnub


    【解决方案1】:

    您缺少的一件事是将整个startNotifications 放入useEffect 挂钩中。没有它,每次组件重新渲染时都会执行所有这些代码。

    export default function Bot({user}) {
        useEffect(() => startNotifications(user), []);
        
        // rest of the code
    }
    

    【讨论】:

      猜你喜欢
      • 2019-09-02
      • 2021-06-11
      • 1970-01-01
      • 2011-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多