如果用户已经登录,我想将其重定向到主页。但是问题是,当我从PrivateRoute()调用useAuth()自定义钩子时,useEffect()未执行,因此没有用户返回信息。我正在为此项目使用Firebase身份验证,这似乎不是问题。我应该使用本地存储来存储用户信息吗?
const AuthContext = createContext();
export const AuthContextProvider = props => {
const auth = Auth();
return <AuthContext.Provider value={auth}>{props.children}</AuthContext.Provider>
};
export const useAuth = () => useContext(AuthContext);
export const PrivateRoute = ({ children, ...rest }) => {
const auth = useAuth();
return (
<Route
{...rest}
render={({ location }) =>
auth.user.email ? (
children
) : (
<Redirect
to={{
pathname: "/authentication",
state: { from: location }
}}
/>
)
}
/>
);
};
const getUser = user => {
const {displayName, email} = user;
return {name: displayName, email};
}
const Auth = () => {
const [user, setUser] = useState({});
useEffect(() => {
firebase.auth().onAuthStateChanged(function(usr){
if(usr) {
const currUser = getUser(usr);
setUser({...user,currUser});
} else{
//Nothing
}
});
}, [])
const signInWithGoogle = () => {
const provider = new firebase.auth.GoogleAuthProvider();
return firebase.auth().signInWithPopup(provider)
.then(result => {
const signedInUser = getUser(result.user);
setUser({...user,signedInUser});
return result.user;
})
.catch(error => {
setUser({});
const errorMessage = error.message;
return errorMessage;
})
}
const signOut = () => {
return firebase.auth().signOut()
.then(() => {
setUser({});
console.log("signed out");
return true;
})
.catch(error => {
const errorMessage = error.message;
console.log(errorMessage);
return false;
});
}
return {
user,
signInWithGoogle,
signOut
}
}
export default Auth;