草庐IT

[Vue warn]: Error in render: “TypeError: Cannot read properties of undefined(reading“category1Name“

man_n 2023-07-06 原文

明明页面正常显示,但是控制台却一直报 如下 错误

 [Vue warn]:渲染错误:"TypeError:无法读取未定义的属性(读取'category1Name')"
中发现的

 Detail 的 vuex 仓库 

import { reqDetail } from "@/api"
export default{
    actions:{
        async getDetail({commit},skuId){
            const result = await reqDetail(skuId)
            console.log(result)
            if(result.code == 200){
                commit("GETDETAIL", result.data)
            }
        }
    },
    mutations:{
        GETDETAIL(state,value){
            state.DetailList = value
        }
    },
    state:{
        DetailList:{}
    },

    getters:{
        categoryView(state){
            return state.DetailList.categoryView 
        },
    }
}

可以看出 DetailList 是通过发送请求获取到的数据,而这个数据,当请求没有返回数据的时候初始状态是一个空的对象或者是数组 

通过 getters 将 DetailList 中的数据提取出来,方便使用

在组件中使用 categoryView 数据

<div class="conPoin">
    <span v-show="categoryView.category1Name" >{{categoryView.category1Name}}</span>
    <span v-show="categoryView.category2Name" >{{categoryView.category2Name}}</span>
    <span v-show="categoryView.category3Name" >{{categoryView.category3Name}}</span>
</div>
computed:{
    ...mapGetters(['categoryView'])
}

会报开头错误

原因:假设我们网络故障,导致DetailList的数据没有请求到,即DetailList是一个空的对象,当我们去调用getters中的return state.DetailList.categoryView时,因为DetailList为空,所以也不存在categoryView,即我们getters得到的categoryView为undefined。所以我们在html使用该变量时就会出现没有该属性的报错。

即:网络正常时不会出错,一旦无网络或者网络问题就会报错。

解决:

        categoryView(state){
            return state.DetailList.categoryView || {}
        },

 在返回值后面 加一个 || ,当属性值为 undefined 时,会返回 || 后面的数据 ,这样就不会报错

如果返回值是对象 后面就加 || { }

如果返回值是数组 后面就加 || [ ]

这个错误不会影响页面,但是起码要明白警报的原因

如果在组件中使用初始可能为空的数据,也可以根据返回的数据类型用一个空的数组或者对象兜底

<template>
  <div class="spec-preview">
    <img :src="imgObj.imgUrl"/>
    <div class="event"></div>
    <div class="big">
      <img :src="imgUrl" />
    </div>
    <div class="mask"></div>
  </div>
</template>

<script>
  export default {
    name: "Zoom",
    props: ["skuImageList"],
    computed:{
      imgObj(){
        return this.skuImageList[0] || {}
      }
    }
  }
</script>

或者直接判断 当这个数据有值时才显示

<template>
  <div class="spec-preview">
    <img :src="skuImageList[0].imgUrl" v-if="skuImageList"/>
    <div class="event"></div>
    <div class="big">
      <img :src="skuImageList[0].imgUrl" v-if="skuImageList"/>
    </div>
    <div class="mask"></div>
  </div>
</template>

<script>
  export default {
    name: "Zoom",
    props: ["skuImageList"]
  }
</script>

有关[Vue warn]: Error in render: “TypeError: Cannot read properties of undefined(reading“category1Name“的更多相关文章

  1. ruby-on-rails - Ruby on Rails : . 常量化 : wrong constant name error? - 2

    我正在使用这个:4.times{|i|assert_not_equal("content#{i+2}".constantize,object.first_content)}我之前声明过局部变量content1content2content3content4content5我得到的错误NameError:wrongconstantnamecontent2这个错误是什么意思?我很确定我想要content2=\ 最佳答案 你必须用一个大字母来调用ruby​​常量:Content2而不是content2。Aconstantnamestart

  2. ruby CSV : How can I read a tab-delimited file? - 2

    CSV.open(name,"r").eachdo|row|putsrowend我得到以下错误:CSV::MalformedCSVErrorUnquotedfieldsdonotallow\ror\n文件名是一个.txt制表符分隔文件。我是专门做的。我有一个.csv文件,我转到excel,并将文件保存为.txt制表符分隔的文件。所以它是制表符分隔的。CSV.open不应该能够读取制表符分隔的文件吗? 最佳答案 尝试像这样指定字段分隔符:CSV.open("name","r",{:col_sep=>"\t"}).eachdo|row|

  3. ruby-on-rails - 更好的替代方法 try( :output). try( :data). try( :name)? - 2

    “输出”是一个序列化的OpenStruct。定义标题try(:output).try(:data).try(:title)结束什么会更好?:) 最佳答案 或者只是这样:deftitleoutput.data.titlerescuenilend 关于ruby-on-rails-更好的替代方法try(:output).try(:data).try(:name)?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.c

  4. ruby - __FILE__ == $PROGRAM_NAME 在 ruby​​ 中是什么意思? - 2

    这个问题在这里已经有了答案:Whatdoes`if__FILE__==$0`meaninRuby(6个答案)关闭6年前。我在审查Ruby代码时偶然发现了这个语法。代码是:if__FILE__==$PROGRAM_NAME#somecode...end我想__FILE__是一个变量,可以让我获取我所在文件的名称?但是$PROGRAM_NAME简化了什么?另外,为什么这个if语句是必需的,因为程序可以使用或不使用它?

  5. ruby-on-rails - 缺失区域;使用 :region option or export region name to ENV ['AWS_REGION' ] - 2

    我知道还有其他相同的问题,但他们没有解决我的问题。我不断收到错误:Aws::Errors::MissingRegionErrorinBooksController#create,缺少区域;使用:region选项或将区域名称导出到ENV['AWS_REGION']。但是,这是我的配置开发.rb:config.paperclip_defaults={storage::s3,s3_host_name:"s3-us-west-2.amazonaws.com",s3_credentials:{bucket:ENV['AWS_BUCKET'],access_key_id:ENV['AWS_ACCE

  6. ruby - File.read ("| echo mystring") 是如何工作的? - 2

    我在我正在处理的一些代码中发现了这一点。它旨在解决从磁盘读取key文件的要求。在生产环境中,key文件的内容位于环境变量中。旧代码:key=File.read('path/to/key.pem')新代码:key=File.read('|echo$KEY_VARIABLE')这是如何工作的? 最佳答案 来自IOdocs:Astringstartingwith“|”indicatesasubprocess.Theremainderofthestringfollowingthe“|”isinvokedasaprocesswithappro

  7. ruby - 如何通过 Rubocop 指示打开 & :read as argument to File. - 2

    我有这个代码File.open(file_name,'r'){|file|file.read}但是Rubocop发出警告:Offenses:Style/SymbolProc:Pass&:readasargumenttoopeninsteadofablock.你是怎么做到的? 最佳答案 我刚刚创建了一个名为“t.txt”的文件,其中包含“Hello,World\n”。我们可以按如下方式阅读。File.open('t.txt','r',&:read)#=>"Hello,World\n"顺便说一下,由于第二个参数的默认值是'r',所以这样

  8. ruby - Chef : Read variable from file and use it in one converge - 2

    我有以下代码,它下载一个文件,然后将文件的内容读入一个变量。使用该变量,它执行一个命令。这个配方不会收敛,因为/root/foo在编译阶段不存在。我可以通过多个聚合和一个来解决这个问题ifFile.exist但我想用一个收敛来完成它。关于如何做到这一点有什么想法吗?execute'download_joiner'docommand"awss3cps3://bucket/foo/root/foo"not_if{::File.exist?('/root/foo')}endpassword=::File.read('/root/foo').chompexecute'join_domain'd

  9. ruby 代码 : why put colon in front of variable name (inside initialize method) - 2

    我遇到了一些Ruby代码,我试图理解为什么变量在initialize方法声明中的名称末尾有冒号。冒号有什么原因吗?attr_reader:var1,:var2definitialize(var1:,var2:)@var1=var1@var2=var2end 最佳答案 那些是关键字参数。您可以按名称而非位置使用它们。例如ThatClass.new(var1:42,var2:"foo")或ThatClass.new(var2:"foo",var1:42)Anarticleaboutkeywordargumentsbythoughtbot

  10. ruby - TypeError(救援条款所需的类或模块) - 2

    我已经使用Stripe一年多了,基于RyanBates的RailsCast插曲发现here.但是,我的错误处理最近停止工作,而且我以前从未见过此错误。我最近开始在Ruby2.1上运行我的应用程序,据我所知,这就是问题所在。这是我的订阅模型中的一个实例方法:beginsave_with_stripe_paymentrescueStripe::InvalidRequestError=>elogger.error"Stripeerrorwhilecreatingcustomer:#{e.message}"logger.errore.backtrace.join("\n")errors.add

随机推荐