无法读取 null 反应的属性“#”

我对反应很陌生,我试图从 firebase 数据库加载个人资料图片。即使该属性不为 null,它仍然会显示 TypeError: Cannot read property 'pfpUrl' of null。


import React from "react"

import { NavLink } from "react-router-dom";

import { useState, useEffect } from "react"

import firebase from "firebase";

import fire from "./firebase"

import { useHistory } from "react"

function Header(){

        const [pfp, setPfp] = useState(null)

        const [userID, setUserID] = useState(null);

        firebase.auth().onAuthStateChanged((user)=>{

            if(user){

                setUserID(user.uid)

                firebase.database().ref("users/"+userID+"/public/profile/pic").on("value", (snapshot)=>{

                    setPfp(snapshot.val().pfpUrl)

                })

            }else{

                

            } 

        })

        function signOut(){

            firebase.auth().signOut().then(()=>{

                console.log("successfully signout")

            })

        }

        return(

            <header>

                

                <div id = "hd-container">

                    <div id = "logo-contain">

                        <NavLink to = "/"><h1>Logo</h1></NavLink>

                    </div>

                    <div id ="search">

                        <div className = "bar">

                            <input id = "searchBar" placeholder = "search"></input>

                        </div>

                        <div className = "searchBtn">

                            <button id = "srhBtn">Search</button>    

                        </div>                   

                    </div>



即使加载了个人资料图片,错误仍然出现,有解决办法吗?


噜噜哒
浏览 114回答 2
2回答

喵喵时光机

您的使用setUserID(user.uid)不会立即导致userID变量包含新值。它只会在组件下次渲染时(而不是这次即将渲染)包含该新值。如果您想在立即出现的数据库查询中使用用户的 UID,则需要在本地使用它的值。const uid = user.uidsetUserID(uid)firebase.database().ref("users/"+ uid +"/public/profile/pic").on("value", (snapshot)=>{&nbsp; &nbsp; setPfp(snapshot.val().pfpUrl)})看到这uid是一个局部变量,其值可以立即在查询中使用。

开心每一天1111

首先,您需要在内部执行代码useEffect,因为每当您设置状态时,api 都会继续触发 api 调用。请参阅下面的代码并尝试在控制台中显示您的值以验证其来自后端。useEffect(() => {&nbsp; &nbsp; firebase.auth().onAuthStateChanged((user)=>{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(user){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; setUserID(user.uid)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; firebase.database().ref("users/"+user.uid+"/public/profile/pic").on("value", (snapshot)=>{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; setPfp(snapshot.val().pfpUrl)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }else{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; })}, [])
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript