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

文章目录

错误描述

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

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

解决方案

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

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

    viewResults(row.id).then(response => {
       for(var i = 1;i<response.data.list.length;i++){
         let obj ={};
         if(response.data.list[i-1].score[3] == response.data.list[i-1].score[4]){
           obj.name = response.data.list[i-1].name
           obj.catename = response.data.list[i-1].catename
           obj.score = response.data.list[i-1].score.substring(0,6)
           }else{
             obj.name = response.data.list[i-1].name
             obj.catename = response.data.list[i-1].catename
             obj.score = response.data.list[i-1].score.substring(0,5)
           }
           this.gridData.push(obj)
       }
     })
    

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

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>