onAuthStateChanged无限循环

onAuthStateChanged无限循环

本文介绍了firebase.auth().onAuthStateChanged无限循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有此代码:

function App() {
  const { setUser } = useContext(UserContext);
  firebase.auth().onAuthStateChanged((user) => {
    console.log("test");
    if (user) {
      console.log("user");
      setUser({ id: user.uid, email: "" });
    } else {
      console.log("null");
      setUser(null);
    }
  });

  return (
    <Container>
      <Router />
    </Container>
  );
}

userContext:

userContext:

const initialState = {
  email: null,
  id: null,
};

export interface IUserContext {
  user: IUser | null;
  setUser: React.Dispatch<IUser | null>;
}

export const UserContext = createContext<IUserContext>({
  user: initialState,
  setUser: () => {},
});

interface IUserContextProvider {
  children: JSX.Element;
}
export function UserContextProvider({ children }: IUserContextProvider) {
  const [user, setUser] = useState<IUser | null>(initialState);
  return (
    <UserContext.Provider value={{ user, setUser }}>
      {children}
    </UserContext.Provider>
  );
}

我试图在登录或注销时设置用户对象.问题在于这会无限循环.我该如何阻止这种情况的发生?我本质上只是想知道某人何时登录或注销.

I am trying to set a user object on log in, or log out. The problem is this keeps looping infinitely. How do I stop this from happening? I essentially just want to know when someone is logged in, or logged out.

推荐答案

这可以由您的 Provider 负责,并在 useEffect 内部运行,如下所示:-

This can be the responsibility of your Provider itself and run inside it's useEffect like so :-


export function UserContextProvider({ children }: IUserContextProvider) {
  const [user, setUser] = useState<IUser | null>(initialState);

useEffect(()=>{
   const unsubscribe = firebase.auth().onAuthStateChanged((user) => {
    console.log("test");
    if (user) {
      console.log("user");
      setUser({ id: user.uid, email: "" });
    } else {
      console.log("null");
      setUser(null);
    }
  });
 return unsubscribe;
},[])

  return (
    <UserContext.Provider value={{ user, setUser }}>
      {children}
    </UserContext.Provider>
  );
}

onAuthStateChanged 仅需要一次性注册,因此 [] 依赖项数组 useEffect 是正确的选择.取消订阅仅在该组件卸载时有效,除非您退出网站,否则该组件不会发生.

The onAuthStateChanged only needs to be registered one-time and so [] dependency array useEffect is the right place for it. The unsubscribe will only work when this component unmounts which won't happen for you unless you exit the website.

这篇关于firebase.auth().onAuthStateChanged无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 21:24