已解决:TypeError: Cannot read properties of undefined (reading ‘name‘ )

深藏阁楼爱情的钟 2024-03-30 14:12 210阅读 0赞

文章目录

    • 错误描述
    • 解决方案

错误描述

TypeError: Cannot read properties of undefined (reading ‘name‘ )

  1. 这个错误在前端中蛮常见的,一般都是提示的这个属性没写对,但是呢,如果仅仅是这么一个简单的错误,也没必要特意写个博客记录一下
  2. 这个错误呢,最常见的解决方式就是查看他提示这个“name”,看看哪个地方写错了

解决方案

  1. 我是在对接口返回值做处理的时候遇到的,简单的来说,就是我需要对接口返回的某个值做处理,如下所示:

    1. viewResults(row.id).then(response => {
    2. console.log(response)
    3. for (var i = 1; i < response.data.list.length; i++) {
    4. if (response.data.list[i - 1].score[3] == response.data.list[i - 1].score[4]) {
    5. this.gridData[i].name = response.data.list[i - 1].name
    6. this.gridData[i].catename = response.data.list[i - 1].catename
    7. this.gridData[i].score = response.data.list[i - 1].score.substring(0, 6)
    8. } else {
    9. this.gridData[i].name = response.data.list[i - 1].name
    10. this.gridData[i].catename = response.data.list[i - 1].catename
    11. this.gridData[i].score = response.data.list[i - 1].score.substring(0, 5)
    12. }
    13. }
    14. })
  2. 具体id错误原因是这样的,vue给对象数组添加对象时for循环只执行一次(我在data中手中加了一个对象,所以只执行了一次),这个其实就是赋值产生的问题,所以上面这么写是错的,正确写法如下所示:

    1. viewResults(row.id).then(response => {
    2. for(var i = 1;i<response.data.list.length;i++){
    3. let obj ={
    4. };
    5. if(response.data.list[i-1].score[3] == response.data.list[i-1].score[4]){
    6. obj.name = response.data.list[i-1].name
    7. obj.catename = response.data.list[i-1].catename
    8. obj.score = response.data.list[i-1].score.substring(0,6)
    9. }else{
    10. obj.name = response.data.list[i-1].name
    11. obj.catename = response.data.list[i-1].catename
    12. obj.score = response.data.list[i-1].score.substring(0,5)
    13. }
    14. this.gridData.push(obj)
    15. }
    16. })

PS:push() 方法可向数组的末尾添加一个或多个元素,并返回新的长度。新元素将添加在数组的末尾。此方法改变数组的长度。

发表评论

表情:
评论列表 (有 0 条评论,210人围观)

还没有评论,来说两句吧...

相关阅读