【问题标题】:TypeError: Cannot read property '_id' of undefined ReactJs?TypeError:无法读取未定义 ReactJs 的属性“_id”?
【发布时间】:2021-05-15 01:29:32
【问题描述】:

我正在尝试使用.map() 方法根据用户ID 获取用户名。我编写的代码对我来说似乎不错,但是,我收到了问题标题中提到的错误,并且页面不会呈现。

请看下图:

这是错误堆栈的图像:

这是我的代码:

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>
  )
}

所以这几乎告诉我usr[i]._id 行不正确,但据我所知,该代码没有任何问题。这就是我向你们伸出援手的原因,因为有几只眼睛会比我只有两只更好。

PD:请多多包涵,因为我是 React.Js 的新手,这是我的第一个应用程序。

【问题讨论】:

    标签: javascript reactjs iteration rendering


    【解决方案1】:

    我想你可能只想要 usr 而不是 usr[i]? map() 为您提供可迭代的单个项目。

    【讨论】:

      猜你喜欢
      • 2013-09-03
      • 2022-07-27
      • 2022-09-23
      • 2019-09-13
      • 2020-11-22
      • 2014-12-24
      • 2020-09-03
      • 1970-01-01
      • 2021-12-06
      相关资源
      最近更新 更多