[英]TypeError: Cannot read properties of undefined (reading 'userName') : React js
I need to render username userData[0].userName
it displays for the first time but if I reload it doesn't render user name.我需要渲染用户名
userData[0].userName
它第一次显示,但如果我重新加载它不会渲染用户名。
const AppHeaderDropdown = () => {
const [userData, setUserData] = useState({})
const getUserData = async () => {
debugger
try {
const res = await fetch('http://localhost:4000/api/authenticate', {
method: 'GET',
headers: {
Accept: 'application/json',
},
credentials: 'include',
})
console.log(res)
const data = await res.json()
console.log('.........here i m in header dropdown...........')
console.log(data[0].userName)
setUserData(data)
if (!res.status === 200) {
const error = new Error(res.error)
throw error
}
} catch (err) {
console.log(err)
}
}
useEffect(() => {
getUserData()
}, [])
TypeError : Cannot read properties of undefined (reading 'userName') TypeError :无法读取未定义的属性(读取“用户名”)
<CDropdownMenu className="pt-0" placement="bottom-end">
61 | <CDropdownHeader className="bg-light fw-semibold py-2">Account</CDropdownHeader>
62 | <CDropdownItem href="#">
> 63 | <CIcon icon={cilUser} className="me-2" />
| ^ 64 | {userData[0].userName}
65 | </CDropdownItem>
66 | <CDropdownItem href="#">
There are two problems:有两个问题:
userData
is {}
.userData
是{}
。 An empty object has no 0
property, so userData[0]
is undefined
on the first render.0
属性,因此在第一次渲染时undefined
userData[0]
。 Remember that your initial state is rendered before any effects are run.userData
as though it were an array, but your initial state is an empty non-array object.userData
就好像它是一个数组,但您的初始 state 是一个空的非数组 object。 It should probably be const [userData, setUserData] = useState([])
(with a []
, an empty array), not const [userData, setUserData] = useState({})
.const [userData, setUserData] = useState([])
(带有[]
,一个空数组),而不是const [userData, setUserData] = useState({})
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.