首页 > 解决方案 > 如何将“用户”对象从我的 TopBar.js 导出到 App.js?

问题描述

TopBar.js 基本上是一个处理身份验证的 AppBar 组件,如果用户登录,我会得到一个对象“用户”,如何将这个“用户”对象导出到 App.js?

如果我设法将其导出到 App.js,我想将其导出到另一个组件创建,该组件可以处理向我的数据库添加内容

我正在使用 React 和 Firebase

这是我的 useEffect 功能

useEffect(() => {
  const unsubscribe = auth.onAuthStateChanged((authUser) => {
    if (authUser) {
      // if user has logged in...
      setUser(authUser)
      if(authUser.displayName){   }
      else{
        return authUser.updateProfile({
          displayName : userName
        });
      }
      
    } else {
      // if user has logged out... 
      setUser(null);
    }
    
  })
  return () => {
    // perform some cleanup actions
    unsubscribe();
  }
}, [user, userName]);

标签: javascriptreactjsfirebasefirebase-realtime-databasefirebase-authentication

解决方案


在该App.js文件中,您可以创建一个处理此问题的上下文。在这种情况下,您有:

const AuthContext = createContext();

现在可以使用 Provider 组件来包装整个应用程序,如下所示:

// the user value comes from the state created
<AuthContext.Provider value={{user}}>
  
</AuthContext.Provider>

useContext然后你可以使用钩子从任何组件访问这个用户值:

const { user } = useContext(AuthContext);

// you can go on and access the `user` value anywhere in the component  

你可以访问这篇文章深入解释它


推荐阅读