开发者问题收集

无法读取未定义的属性(读取‘名称’):ReactJs

2021-10-19
208

当我尝试记录数据时,控制台中有数据,但我无法使用它。

我的数据对象如下所示:

{_id:'616bf82d16a2951e53f10da4',名称:'abd',电子邮件:' [email protected] ',电话:'1234567890',工作:'singer',… }

accessToken: “eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjYxNmJmODJkMTZhMjk1MWU1M2YxMGRhNCIsImlhdCI6MTYzNDYyMDk3MiwiZXhwIjoxNjM1MDUyOTcyfQ.b9NZB-ogrdu_SulT1xJ8h62a HdyAo2jzTny2qakeaHY"

cpassword: "$2a$12$BZ17rY63qrq.Fw9wC29A.eabcuAHSY0mXfxSvcpxOFGfUeW4NUkMO"

电子邮件: " [email protected] "

名称:“abd”

电话:“1234567890”

tokens:(3)[{…},{…},{…}]

作品:“歌手”

__v:3

_id:“616bf82d16a2951e53f10da4”

[[原型]]:对象

import "./about.css"
import {useHistory} from "react-router-dom"


export default function About() {
    const history=useHistory();
    const [userData,setUserData]=useState();
    const callAboutPage=async()=>{
        try {
            const res=await fetch("/about",{
                method:"GET",
                headers:{
                    Accept:"application/json",
                    "Content-Type":"application/json"
                },
                credentials:"include"
            })
            const data=await res.json();
            console.log(data);
            setUserData(data);

            if(!res.status===200){
               const error=new Error (res.error)
               throw error
            }
            
        } catch (error) {
            console.log(error)
            history.push("/login")
        }
    }
    
  useEffect(() => {
     callAboutPage();
  }, [])

    return (
        <div className="abt-body">
            <div className=" d-flex justify-content-center align-items-center about">
                
                Name:{userData.name}
                <br />
                Id:{userData._id}
                <br />
                Email:{userData.email}
                <br />
                Phone:{userData.phone}
                <br />
                Work:{userData.work}
             
                

                

            </div>
           

                <div class="card-footer text-muted d-flex justify-content-center align-items-center">
    Designed and Developed by : Harsh Raj Ambastha
  </div>
        </div>
    )
}
2个回答

您可以尝试使用 Javascript 可选链接: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

尝试将运算符添加到每个字段:

userData?.name
userData?._id

等等。

Jonathan
2021-10-19

这是因为您将初始值设置为空,这将被解释为原始值。因此,当它最初呈现时,它会发现您正在尝试访问不存在的原始值的属性。将初始值设置为空对象,它将不再在此处抛出错误。 useState({})

2021-10-19