有没有办法避免在Next.js上调用热量加载函数

发布于 2025-02-03 12:02:33 字数 796 浏览 2 评论 0原文

我有一个非常简单的钩子,可以按预期工作:

const subscriptions: Subscription[] = []

const useEvents = () => {
  const subscribe = (type: Type, callback: () => void) => {
    const id = nanoid(8)
    subscriptions.push({
      id,
      type,
      callback,
    })
    return () => {
      subscriptions.splice(
        subscriptions.findIndex((s) => s.id === id),
        1
      )
    }
  }

  const dispatch = (type: Type) => {
    for (const subscription of subscriptions.filter((s) => s.type === type)) {
      subscription.callback()
    }
  }
  return { subscribe, dispatch }
}

我订阅:

useEffect(() => {
  subscribe("run", () => {
    console.log("RUN!!")
  })
}, [])

问题是,当应用程序正在热填充订阅时,再次调用订阅并重复了回调,是否有任何方法可以避免这种情况?

I have a very simple hook that works as intended:

const subscriptions: Subscription[] = []

const useEvents = () => {
  const subscribe = (type: Type, callback: () => void) => {
    const id = nanoid(8)
    subscriptions.push({
      id,
      type,
      callback,
    })
    return () => {
      subscriptions.splice(
        subscriptions.findIndex((s) => s.id === id),
        1
      )
    }
  }

  const dispatch = (type: Type) => {
    for (const subscription of subscriptions.filter((s) => s.type === type)) {
      subscription.callback()
    }
  }
  return { subscribe, dispatch }
}

I subscribe so:

useEffect(() => {
  subscribe("run", () => {
    console.log("RUN!!")
  })
}, [])

The problem is that when the app is hot-reloading subscribe is called again and the callback duplicated, is there any way to avoid this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文