javascript - 如何将“用户”对象从我的 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]);
解决方案
在该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
你可以访问这篇文章深入解释它
推荐阅读
- html - 我可以将背景图像平铺一定次数吗?
- php - 如何使用 url 字符串中的数组来简化 php 代码
- python - How do set the amount of list elements equal to the number of characters in a string?
- javascript - 如何在 JavaScript 中显示与标签分开的帖子标签?
- javascript - 如何将 javascript 添加到个人 tumblr 博客文章?
- node.js - 如何使用带有节点 js 的谷歌驱动器 API 列出谷歌团队驱动器中的所有文件
- python - 当两个数据框之间的 if 语句匹配时,数据框将使用来自其他数据框的值附加新列
- ios - SWIFT 将参数从 VC 传递到 UIView 让我抓狂
- javascript - 使用导航栏滚动 div
- javascript - 来自另一个组件的 React Router Link 不起作用