简体   繁体   English

TypeError:在 useState 中传递 object 时,无法读取未定义的属性“名称”

[英]TypeError: Cannot read property 'name"' of undefined in react when passing object in useState

My issue is from route getting the response in json format.我的问题来自以 json 格式获得响应的路线。 And when consoling it gives the data as well but when i passing in setProfileData(data) then updated state gives undefined.并且在安慰时它也给出了数据,但是当我传入 setProfileData(data) 然后更新的 state 给出未定义的。

But when i gives like setProfileData(data.user.name) then its gives that specific value.但是当我像 setProfileData(data.user.name) 这样给出时,它会给出那个特定的值。

Here my server route这是我的服务器路由

router.get('/user/:id',async(req,res)=>{
  try {
    const user = await User.findOne({_id:req.params.id}).select('-password')
    const post = await Post.find({postedBy:req.params.id}).populate('postedBy', '_id name')
    
    return res.json({user,post})
        
    } catch (error) {
        return res.json(error)
    }
})

Here is my Component UserProfile这是我的组件用户配置文件

import React,{useContext,useEffect,useState} from 'react';
import {useHistory,useParams} from 'react-router-dom'
import {UserContext} from '../../App'

const UserProfile = ()=>{
    const [newProfile,setProfileData] = useState(null)
    const {state,dispatch} = useContext(UserContext)
    
    const {userId} = useParams()
    console.log(userId)
    useEffect(()=>{
        fetch(`/user/${userId}`,{
            headers:{
                'Authorization': 'Bearer '+localStorage.getItem('jwt')
            }
        }).then((res)=>{
            return res.json()
        }).then((data)=>{
            console.log(data)
           setProfileData(data)
            
        })
    },[])
    return (
        <div style={{width:'555px',margin:"0px auto"}}>
            <div style={{display:"flex",justifyContent:"space-around",margin:'18px 0px',borderBottom:"1px solid grey"}}>
                <div><img style={{width:"160px",height:"160px",borderRadius:"80px"}}
                src="https://images.unsplash.com/photo-1550927407-50e2bd128b81?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60" alt="Profile Pic"/>
                </div>
                <div>
    <h4>{newProfile.user.name}</h4>
                 <div style={{display:"flex",justifyContent:"space-around",width:"108%"}}>
                     <h5>40 Posts</h5>
                     <h5>40 Followers</h5>
                     <h5>40 Followings</h5>
                 </div>
                 </div>
            </div>
            <div className="gallery">
                 {
                    // userProfile.map((item)=>{
                    //     return (
                    //         <img key={item._id} className="item" src={item.file} alt={item.title}/>
                    //     )
                    // })
                }
                
           
               
             
            </div>
        </div>
    );
}

export default UserProfile;

{newProfile.user.name} giving type undefined {newProfile.user.name} 给出类型未定义

newProfile is null when the component start working.当组件开始工作时, newProfile为 null。 You must check before accessing it in the render method:您必须在 render 方法中访问它之前进行检查:

  {newProfile != null ?
                        <div>
                            <h4>{newProfile.user.name}</h4>
                            <div style={{ display: "flex", justifyContent: "space-around", width: "108%" }}>
                                <h5>40 Posts</h5>
                                <h5>40 Followers</h5>
                                <h5>40 Followings</h5>
                            </div>
                        </div>
                        : 'loading'}

or use the default value in the useState hook或使用useState挂钩中的默认值

Full version:完整版本:

import React, { useContext, useEffect, useState } from 'react';
import { useHistory, useParams } from 'react-router-dom'
import { UserContext } from '../../App'
import { Divider } from 'material-ui';

const UserProfile = () => {
    const [newProfile, setProfileData] = useState(null)
    const { state, dispatch } = useContext(UserContext)

    const { userId } = useParams()
    console.log(userId)
    useEffect(() => {
        fetch(`/user/${userId}`, {
            headers: {
                'Authorization': 'Bearer ' + localStorage.getItem('jwt')
            }
        }).then((res) => {
            return res.json()
        }).then((data) => {
            console.log(data)
            setProfileData(data)

        })
    }, [])
    return (
        <div style={{ width: '555px', margin: "0px auto" }}>
            <div style={{ display: "flex", justifyContent: "space-around", margin: '18px 0px', borderBottom: "1px solid grey" }}>
                <div><img style={{ width: "160px", height: "160px", borderRadius: "80px" }}
                    src="https://images.unsplash.com/photo-1550927407-50e2bd128b81?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60" alt="Profile Pic" />
                </div>
                <div>
                    {newProfile != null ?
                        <div>
                            <h4>{newProfile.user.name}</h4>
                            <div style={{ display: "flex", justifyContent: "space-around", width: "108%" }}>
                                <h5>40 Posts</h5>
                                <h5>40 Followers</h5>
                                <h5>40 Followings</h5>
                            </div>
                        </div>
                        : 'loading'}

                </div>
            </div>
            <div className="gallery">
            </div>
        </div>
    );
}

export default UserProfile;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 “TypeError:使用 useState 和 useEffect 时无法读取未定义的属性‘名称’” - “TypeError: Cannot read property 'name' of undefined” when using useState and useEffect TypeError:无法读取 React 中未定义的属性“多对象中的状态名称” - TypeError: Cannot read property 'state name in much object' of undefined in React 反应:类型错误:无法读取未定义的属性“名称” - REACT: TypeError: Cannot read property 'name' of undefined 当我想访问对象详细信息时,React JS引发“ TypeError:无法读取未定义的属性&#39;名称&#39;”错误 - React JS throw “TypeError: Cannot read property 'name' of undefined” error when i want to access object details 无法读取未定义的属性“材料”。 用嵌套对象反应useState - Cannot read property 'Materials' of undefined. React useState with a nested object React TypeError:在传递道具时无法读取未定义的属性“map” - React TypeError: Cannot read property 'map' of undefined on passing props React Native TypeError:无法读取未定义的属性“名称” - React Native TypeError: Cannot read property 'name' of undefined 反应错误类型错误:无法读取未定义的属性“名称” - React Error TypeError: Cannot read property 'name' of undefined 反应:未捕获的类型错误:无法读取 mapStateToProps 中未定义的属性“名称” - React: Uncaught TypeError: Cannot read property 'name' of undefined in mapStateToProps Uncaught TypeError:无法读取React中未定义的属性“名称” - Uncaught TypeError: Cannot read property 'name' of undefined in React
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM