Javascript Can';t访问React JSX中的嵌套对象JSON

Javascript Can';t访问React JSX中的嵌套对象JSON,javascript,reactjs,Javascript,Reactjs,我可以在这里访问结果中的JSON对象 useEffect(() => { fetch(`/user/${userid}`,{ method:'get', headers:{ "Authorization":`Bearer ${localStorage.getItem('token')}`} }).then(res=>res.json()) .then(result=>{

我可以在这里访问结果中的JSON对象

useEffect(() => {
    fetch(`/user/${userid}`,{
        method:'get',
        headers:{
            "Authorization":`Bearer ${localStorage.getItem('token')}`}

    }).then(res=>res.json())
        .then(result=>{
            console.log(result.user.name) //I can access JSON objects in the results here//
            setProfile(result)
        })
        .catch(err=>console.log(err))

}, [])
我可以在更改状态时访问JSON,但它会抛出错误,如
UserProfile.user
未定义,
UserProfile.posts.length
在呈现JSX时未定义。为了访问嵌套数据,我尝试创建更多的状态变量。它可以工作,但代码已经变长了。我在各种网站上寻找解决方案,但没有找到。谁来帮我

return (
    <>
        {
            UserProfile?<div style={{maxWidth:'800px',margin:"0px auto"}}>

                    <div style={{
                        display:"flex",
                        justifyContent:'space-around',
                        margin:"18px 0px"
                    }}>
                        <div>
                            <img style={{borderBottom:"1px solid grey",width:"160px",height:"160px",borderRadius:"80px"}} src="https://images.unsplash.com/photo-1569466896818-335b1bedfcce?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60"/>

                        </div>
                        <div>
                            <h4>{UserProfile?UserProfile.user.name:"Loading..."}</h4>

                            <div style={{display:"flex",justifyContent:"space-between",width:"100%"}}>
                                <h6>{UserProfile.posts.length} posts &nbsp;</h6>

                                <button onClick={()=>followUser()} className="btn waves-effect waves-light #64b5f6 blue lighten-2" type="button" name="action">Follow</button>

                            </div>
                        </div>
                    </div>


                    <div className="gallery">
                        {
                            UserProfile.posts.map((item)=>{
                                return(
                                    <img className="item" key={item._id} src={item.photo}/>
                                )

                            })

                        }
                    </div>
                </div>:
                <h1>Loading:</h1>

        }
    </>
)

export default Profile
返回(
{
用户档案?
{UserProfile?UserProfile.user.name:“正在加载…”
{UserProfile.posts.length}posts
followUser()}className=“btn波浪效果波浪灯光#64b5f6蓝色发光-2”type=“button”name=“action”>跟随
{
UserProfile.posts.map((项)=>{
返回(
)
})
}
:
加载:
}
)
导出默认配置文件

根据代码和您的输入,问题可能是因为您试图在变量可访问之前访问它们

useffect()
中进行异步API调用时,可能需要一些时间才能获取数据。但是,由于您在获取数据之前访问数据,会出现错误,如
'UserProfile.user未定义'
'UserProfile.posts.length'未定义

要避免此类错误,请确保添加如下所示的检查

        <>
           {
              UserProfile && 
                <div style={{maxWidth:'800px',margin:"0px auto"}}>
                    <div style={{
                        display:"flex",
                        justifyContent:'space-around',
                        margin:"18px 0px"
                    }}>
                        <div>
                            <img style={{borderBottom:"1px solid grey",width:"160px",height:"160px",borderRadius:"80px"}} src="https://images.unsplash.com/photo-1569466896818-335b1bedfcce?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60"/>
         
                        </div>
                        <div>
/* -----> modify it here*/  <h4>{UserProfile ? UserProfile.user && UserProfile.user.name:"Loading..."}</h4>
         
                            <div style={{display:"flex",justifyContent:"space-between",width:"100%"}}>
/* -----> modify it here*/  <h6>{UserProfile && UserProfile.posts && UserProfile.posts.length} posts &nbsp;</h6>
                 
                            <button onClick={()=>followUser()} className="btn waves-effect waves-light #64b5f6 blue lighten-2" type="button" name="action">Follow</button>
                            
                        </div>
                        </div>
                        </div>
                       
                        
                        <div className="gallery">
                            {
                              UserProfile.posts.map((item)=>{
                                 return(
                                  <img className="item" key={item._id} src={item.photo}/>
                                 )
                              })
                            }
                        </div>
                </div> 
                :
                <h1>Loading:</h1>
             }
        </>

{
用户配置文件&&
/*--->在这里修改它*/{UserProfile?UserProfile.user&&UserProfile.user.name:“正在加载…”
/*--->在这里修改它*/{UserProfile&&UserProfile.posts&&UserProfile.posts.length}posts
followUser()}className=“btn波浪效果波浪灯光#64b5f6蓝色发光-2”type=“button”name=“action”>跟随
{
UserProfile.posts.map((项)=>{
返回(
)
})
}
:
加载:
}

我找到了解决方案。通过将初始状态设置为null,我解决了这个问题。谢谢你回答我的问题

//my initial useState declaration//
const [userProfile,setUserProfile]=useState([])
//Solution//
const [userProfile,setUserProfile]=useState(null)



我是新手,所以我遇到了问题。

您的初始状态是什么?对象的形状是什么?我会保留所有以小写字母开头的局部变量:userProfile,而不是userProfile。请记住,大写字母在React/JSX中起着特殊的作用。此外,我怀疑您正在使用setProfile作为userProfile的setter:React指南建议遵循以下规则:userProfile-setUserProfile。