TypeError: Cannot read property 'name"' of undefined in react when passing object in useState
TypeError: Cannot read property 'name"' of undefined in react when passing object in useState
我的问题是路由获取 json 格式的响应。当安慰它时它也给出数据但是当我传入 setProfileData(data) 然后更新状态给出未定义的。
但是当我给出类似 setProfileData(data.user.name) 时,它会给出特定值。
这是我的服务器路由
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)
}
})
这是我的组件用户配置文件
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} 给出类型未定义
当组件开始工作时,newProfile
为空。在 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'}
或者使用 useState
钩子中的默认值
完整版:
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;
我的问题是路由获取 json 格式的响应。当安慰它时它也给出数据但是当我传入 setProfileData(data) 然后更新状态给出未定义的。
但是当我给出类似 setProfileData(data.user.name) 时,它会给出特定值。
这是我的服务器路由
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)
}
})
这是我的组件用户配置文件
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} 给出类型未定义
newProfile
为空。在 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'}
或者使用 useState
钩子中的默认值
完整版:
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;