如果未卸载App组件,如何在useEffect挂钩清理功能中分离Firebase侦听器

时间:2020-04-15 14:55:10

标签: firebase google-cloud-firestore react-hooks use-effect

我使用(firebase)注销时未触发useEffect清理功能,并且收到错误 onSnapshot中的未捕获错误:FirebaseError:缺少权限或权限不足。 一旦我重定向到登录/注册页面。

我了解到,如果卸载组件,则会触发清理功能,但就我而言,应用程序组件不会卸载(并且不应卸载),因此侦听器不会被分离

   function App() {
     const [currentUser, setCurrentUser] = useState('')

     useEffect(() => {
      let unsubscribeFromAuth = null;

      unsubscribeFromAuth = auth.onAuthStateChanged(async userAuth => {
        if(userAuth) {
          const userRef = await createUserProfileDocument(userAuth)

          userRef.onSnapshot(snapshot => {
            setCurrentUser({
              id: snapshot.id,
              ...snapshot.data()
            })
          })
         }

        setCurrentUser(userAuth)
      })

      // the cleaning function is not being triggered because the App component is not unmounting (it shouldn't unmount anyways)
      return () => unsubscribeFromAuth()
    },[])

    return (
      <div className="App">
        <Switch>
          <Route exact path="/">
            {
              currentUser
                ? <Redirect from="/" to="/userpage" />
                : <SignInAndSignUpPage currentUser={currentUser} />
            }
          </Route>

          <Route path='/userpage'>
            {
              !currentUser
                ? <Redirect from="/userpage" to="/" />
                : <UserPage user={currentUser} />
            }
          </Route>
        </Switch>
      </div>
    );
  }

我的Firebase安全规则:

service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if request.auth.uid != null;
    }   
  }
}

位于用户页面上的我的退出按钮:

 <button
    onClick={() => {
      auth.signOut();
    }}
 >
   SIGN OUT
 </button>

0 个答案:

没有答案