【问题标题】:TypeError: Cannot read properties of undefined (reading 'userName') : React jsTypeError:无法读取未定义的属性(读取“用户名”):React js
【发布时间】:2022-01-01 17:38:04
【问题描述】:

我需要渲染用户名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:无法读取未定义的属性(读取“用户名”)

<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="#">

【问题讨论】:

    标签: javascript reactjs jsx


    【解决方案1】:

    有两个问题:

    1. 主要问题是您的初始userData{}。空对象没有0 属性,因此userData[0] 在第一次渲染时是undefined。请记住,您的初始状态是在运行任何效果之前呈现的。
    2. 您正在使用userData,就好像它是一个数组,但您的初始状态是一个空的非数组对象。它可能应该是const [userData, setUserData] = useState([])(带有[],一个空数组),而不是const [userData, setUserData] = useState({})

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-17
      • 1970-01-01
      • 2020-12-24
      • 1970-01-01
      • 2019-07-27
      • 2016-05-08
      • 1970-01-01
      相关资源
      最近更新 更多