微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

带回调的 Nextjs 侦听器自行执行

如何解决带回调的 Nextjs 侦听器自行执行

我一直在为我的 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 函数中,我什至尝试取消订阅和重新订阅,但这也不起作用。看起来像这样 (第一次通知

1. Image

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

2. Image

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

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

解决方法

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。