【问题标题】:passing variable from page to page react将变量从页面传递到页面反应
【发布时间】:2021-04-05 15:04:39
【问题描述】:

我有一个来自 firebase 的 uid,但它是这样存储的:

checkout.js

 firebase.auth().onAuthStateChanged((user) => {
  if(user) {
    console.log(user.uid)
   }
 });

user.uid 存储我需要传递到另一个页面的 uid。此 uid 存储在 checkout.js 中,我需要将其发送到 profile.js 以使用那里的 uid。我该怎么做? 如果需要更多代码,请告诉我。我正在使用反应/js

【问题讨论】:

    标签: javascript reactjs firebase firebase-authentication


    【解决方案1】:

    我实际上只是将该代码复制并粘贴到profile.js 中,并且它起作用了。 ?

    【讨论】:

    • 这可能有效,但远非正确(和更好)的方式来实现这一点。这可以使用 Redux 等状态管理框架或内置 Context 或使用 cookie 来完成。
    【解决方案2】:

    使用上下文存储

    创建商店和钩子

    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
    

    【讨论】:

      猜你喜欢
      • 2023-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-07
      • 2017-12-30
      相关资源
      最近更新 更多