如何正确取消订阅 Firebase 实时数据库的 onValue 侦听器

How to properly unsubscribe to an onValue listener for Firebase Realtime Database

背景:这是一个练习待办事项列表应用程序,我在其中使用 onValue 来监听实时数据库中待办事项列表的更改,然后将其映射到前端的任务数组。

我以前在按以下方式使用 onValue 时出现内存泄漏错误 - 当我没有取消订阅我的 onValue 侦听器时:

  useEffect(
    () => {
      if (user) {

    onValue(ref(database, `users/${user}/tasks`), (snapshot) => {
      const todos = snapshot.val();

      const tasks = [];

      for (let id in todos) {
        tasks.push({ ...todos[id], id: id })
      }

      setTasks(tasks)
    })
    
  } else {
    setTasks([])
  }
}, [user])

我从这里的其他一些问题中看到 onValue return 是一个取消订阅函数,我还看到一个答案,通过将 return 添加到 onValue 行,我可以取消订阅 - 我在下面尝试这样做:

 useEffect(
    () => {
      if (user) {

        return onValue(ref(database, `users/${user}/tasks`), (snapshot) => {
          const todos = snapshot.val();

          const tasks = [];

          for (let id in todos) {
            tasks.push({ ...todos[id], id: id })
          }

          setTasks(tasks)
        })
        
      } else {
        setTasks([])
      }
    }, [user])

这似乎对我有用,但我可以得到一些帮助来确认这是取消订阅此 onValue 侦听器的正确方法吗?

您的 useEffect 回调需要 return 取消订阅函数,以便 React 可以在不再需要 component/hook 时调用它。通过 returning 来自 onValue 的 return 值,您可以确保在不再需要 component/hook 时取消订阅 onValue。如果这是你想要完成的(看起来是这样),那么这看起来确实是正确的。