[英]TypeError: Cannot read property '_id' of undefined ReactJs?
I am trying to get the name of a user based on the user id, using a .map()
method.我正在尝试使用.map()
方法根据用户 ID 获取用户的名称。 The code that I wrote seems good to me, however, I get the error mentioned in the question title and the page won't render.我编写的代码对我来说似乎不错,但是,我收到问题标题中提到的错误并且页面不会呈现。
Please see the image below:请看下图:
Here's an image of the error stack:这是错误堆栈的图像:
And here's the code I have:这是我的代码:
import { SearchBox } from "../SearchBox"
import { StyledNavBar, NavSection, StyledLink, StyledLogo } from "./styles"
import logo from './Logo2.png'
import { useDispatch } from "react-redux"
import { useHistory } from "react-router"
import axios from "axios"
import { useEffect, useState } from "react"
function useApi() {
const userId = localStorage.getItem('userId')
const dispatch = useDispatch()
const [UserNames, setUserNames] = useState()
useEffect(() => {
async function getData() {
try {
const { data } = await axios({
method: 'GET',
baseURL: process.env.REACT_APP_SERVER_URL,
url: '/users'
})
console.log(data)
dispatch(setUserNames(data))
}catch(error){
dispatch(console.log(error))
}
}
getData()
}, [])
return { userId, UserNames }
}
export const NavBar = function({}) {
const { userId, UserNames } = useApi()
console.log(UserNames)
const token = localStorage.getItem('token')
const dispatch = useDispatch()
const history = useHistory()
function handleClick(){
dispatch({type: 'USER_LOGOUT'})
localStorage.clear()
history.push('/')
}
return(
<StyledNavBar>
<NavSection>
{!token && <StyledLink to='/login'>Ingresar</StyledLink>}
{!token && <StyledLink to='/signup'>Registrarse</StyledLink>}
<StyledLink to='/'>Categorías</StyledLink>
<StyledLink to='/'><StyledLogo src={logo} /></StyledLink>
{token && <StyledLink to='/'>Mis Transacciones</StyledLink>}
{token && <StyledLink to='/sellproduct'>Vender</StyledLink>}
{!!UserNames && UserNames.length > 0 && UserNames.map((usr, i) => {
return usr[i]._id === userId ?
<p>{usr[i].name}</p>
:
''
})}
<SearchBox />
{token && <button type='button' onClick={handleClick}>Cerrar Sesión</button>}
</NavSection>
</StyledNavBar>
)
}
So it's pretty much telling me that the usr[i]._id
line is not correct, but as far as I can see nothing is wrong with that code.所以它几乎告诉我usr[i]._id
行不正确,但据我所知,该代码没有任何问题。 That is the reason why I am reaching out to you guys, since several eyes will be better than my only two.这就是我向你们伸出援手的原因,因为有几只眼睛会比我只有两只眼睛好。
PD: Please bear with me as I am new to React.Js and this is my first app. PD:请多多包涵,因为我是 React.Js 的新手,这是我的第一个应用程序。
I think you might just want usr and not usr[i]?我想你可能只想要 usr 而不是 usr[i]? The map() gives you the individual item from the iterable. map() 为您提供可迭代的单个项目。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.