这是我的错误类型错误:无法读取空的属性'email'
这是我的提供商组件
import React, { useState } from 'react'
import { whatchUserChanges } from '../services'
export const AuthContext = React.createContext()
export default function AuthContextProvider(props) {
const [state, setState] = useState({
isLoggedIn: false,
user: null,
authReady:false
})
useState(() => {
whatchUserChanges((user) => {
if (user) {
setState({
isLoggedIn: true,
user: user,
authReady:true
})
} else {
setState({
isLoggedIn: false,
user: null,
authReady:true
})
}
})
}, [])
return (
<AuthContext.Provider value={state}>
{props.children}
</AuthContext.Provider>
)
}
这是我想要呈现我的属性电子邮件的组件
import React, { useContext } from "react"
import { AuthContext } from "../../context/auth"
export default function Dashboard() {
const contextAuth = useContext(AuthContext)
console.log(contextAuth.user.email)
return (
<div className="Dashboard">El email es {contextAuth.user.email}</div>
)
}
当我删除这个部分时
{contextAuth.user.email}
我在第一次渲染中看到contextAuth.user.emai是null,但在控制台的第二次渲染中contextAuth.user.emai不是null。
这是我的存储库:https://github.com/RotomFormProgramador/learnfirebase
我是如何解决这个问题的?
处理user
是null
的情况
export default function Dashboard() {
const contextAuth = useContext(AuthContext)
const user = contextAuth.user || {};
return (
<div className="Dashboard">El email es {contextAuth.user.email}</div>
)
}
或者如果用户未登录则显示不同的消息
export default function Dashboard() {
const {user, isLoggedIn} = useContext(AuthContext)
if (isLoggedIn){
return (
<div className="Dashboard">El email es {user.email}</div>
);
}
return (<div>User is not logged in</div>);
}