0

这是我的错误 TypeError: Cannot read property 'email' of null

这是我的提供者组件

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 为空,但在控制台中的第二个渲染中 contextAuth.user.emai 不为空。

这是我的存储库:https ://github.com/RotomFormProgramador/learnfirebase

我是如何解决这个问题的?

4

1 回答 1

0

处理 is 的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>);
}
于 2020-03-13T21:01:35.547 回答