日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

解決Uncaught (in promise) TypeError: Cannot read properties of undefined (reading ‘id‘)報(bào)錯(cuò)

作者:前端百草閣 更新時(shí)間: 2023-07-04 編程語言

項(xiàng)目場景:

做黑馬的人資項(xiàng)目時(shí),要讀取store中的userInfo里的id值,報(bào)Uncaught (in promise) TypeError: Cannot read properties of undefined (reading ‘id’)錯(cuò),起初以為是axios發(fā)異步請求的問題,直到后來一直嘗試,終于找到了問題所在!


問題描述

連續(xù)訪問對象里的值

例如:我現(xiàn)在user模塊下的state是這樣的,userInfo里的值要等到發(fā)請求才會填充

state: {
    token: getToken() || '',
    userInfo: {

    }

請求回來的值是這樣的
在這里插入圖片描述

那我現(xiàn)在要是還沒請求,userInfo 就還是個(gè)空對象,訪問store.user.state.userInfo.data,就是為undefined
但是!!最重要的點(diǎn)來了,如果你接著訪問store.user.state.userInfo.data.id,這時(shí)候就不是簡單的undefined
而是 控制臺報(bào)錯(cuò),Uncaught (in promise) TypeError: Cannot read properties of undefined (reading ‘id’)

原因分析:

從上面的講解來看,不難知道,你要是訪問對象里不存在的屬性,結(jié)果是undefined,但如果你接著還往下訪問,那就會報(bào)錯(cuò)


解決方案:

有兩個(gè)辦法解決

1.在userInfo下加一個(gè)data

state: {
    token: getToken() || '',
    userInfo: {
      data: {}
    }
  }

像這樣,你訪問userInfo.data就是一個(gè)空對象,再訪問userInfo.data.id的話,就是undefined啦! 就不會報(bào)錯(cuò)了

2.利用?.的訪問方式

store.state.user.userInfo?.data?.id, 利用?.的方式訪問對象中的屬性,要是有一個(gè)屬性找不到的話,就會立即返回undefined,
也不會出現(xiàn)報(bào)錯(cuò)的情況

store.state.user?.data?.id

原文鏈接:https://blog.csdn.net/m0_57524265/article/details/131441971

  • 上一篇:沒有了
  • 下一篇:沒有了
欄目分類
最近更新