簡體   English   中英

無法在 React JSX 中訪問嵌套對象 JSON

[英]Can't access nested Objects JSON in React JSX

我可以在此處的結果中訪問 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))

}, [])

我可以在更改 State 時訪問 JSON 但它會引發錯誤,例如UserProfile.user未定義, UserProfile.posts.length在渲染 JSX 時未定義。 要訪問嵌套數據,我嘗試創建更多 state 變量。 它可以工作,但是代碼變長了。 我在各種網站上尋找解決方案,但找不到。 任何人幫助我。

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

根據代碼和您的輸入,問題可能是因為您試圖在變量可訪問之前訪問它們。

當您在useEffect()中進行異步 API 調用時,可能需要一些時間才能獲取數據。 但是,當您在獲取數據之前訪問數據時,會出現'UserProfile.user is undefined'之類的錯誤, 'UserProfile.posts.length' is undefined '

為避免此類錯誤,請確保添加如下所示的檢查

        <>
           {
              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>
             }
        </>

我得到了解決方案。 我通過將初始 state 設置為 null 解決了這個問題。 謝謝你回答我的問題。

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


我是新手,所以我遇到了問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM