我有一个来自 firebase 的 uid,但它是这样存储的:
checkout.js
firebase.auth().onAuthStateChanged((user) => {
if(user) {
console.log(user.uid)
}
});
user.uid
存储我需要传递到另一个页面的 uid。此 uid 存储在 checkout.js
中,我需要将其发送到 profile.js
才能在那里使用 uid。我该怎么做?
如果需要更多代码,请告诉我。我正在使用 react/js
答案 0 :(得分:1)
我实际上只是将该代码复制并粘贴到 profile.js
中并且它起作用了。 ?
答案 1 :(得分:1)
使用上下文存储
创建商店和钩子
const FirebaseAuthContext = createContext()
export function useAuth() {
const context = useContext(FirebaseAuthContext)
if (!context && typeof window !== 'undefined') {
throw new Error(`useAuth must be used within a FirebaseAuthContext`)
}
return context
}
创建提供者
export function FirebaseAuthProvider(props) {
const [authState, setAuthState] = useState({
isLoggedIn: false,
currentUser: null,
pending: true,
})
useEffect(() => {
const unregisterAuthObserver = auth().onAuthStateChanged(async (currentUser) => {
if (currentUser) {
setAuthState({. isLoggedIn: true, pending: false, currentUser})
} else {
setAuthState({ ...authState, currentUser: null, pending: false })
}
})
return () => unregisterAuthObserver()
}, [])
return <FirebaseAuthContext.Provider value={authState}>{props.children}</FirebaseAuthContext.Provider>
使用提供程序包装您的应用
<FirebaseAuthProvider><App /></FirebaseAuthProvider>
然后在您需要验证用户的任何地方。
const { currentUser, pending } = useAuth();
if (currentUser && pending) //pending authentication
if (currentUser) // user is login, uid is in currentUser.uid