【问题标题】:TypeError: Cannot read properties of undefined (reading 'id') when trying to delete an entryTypeError:尝试删除条目时无法读取未定义的属性(读取“id”)
【发布时间】:2021-09-20 09:07:14
【问题描述】:

我似乎无法删除 Firebase 上已分配给用户 uid 的记录,例如对象中的对象。

<template>
  <v-container id="tutorials">
      <h1>Gigs Available!</h1>
           <!-- loop over the tutorials -->
           <div  class="Agrid d-grid">
           <div
           class="Amodule  back"
           v-for="gig in allGigs"
           :key="gig">
           <div class="fill-height">
             <v-container >
              <a @click.prevent="deleteGigs(gig)" class="card-link">
                 <v-icon color=red>mdi-delete</v-icon>
               </a>
             <br>
             <div class="d-flex align-start">
               <h3 class="j-title center mb-00">{{ gig.gigtitle}}</h3>
             </div>
             <h6 class="">{{gig.companyname}}</h6>
             <v-row class="d-flex ">
               <p class="col-tres mdi mdi-clock text--secondary"> {{ gig.vacanttype }} </p>
               <p class="col-tres mdi mdi-earth text--secondary"> {{ gig.giglocation }} </p>
               <p class="col-tres mdi mdi-calendar text--secondary">{{gig.gigdate}} </p>
             </v-row>
             <v-divider class="mx-4"></v-divider>
             <h5 class="left text-body-2">Company description</h5><br>
             <p class="content"> {{ gig.companydescription}}</p><br>
             <h5 class="left text-body-2">Gig description</h5><br>
             <p class="content"> {{ gig.gigdescription}}</p><br>
             <h5 class="left text-body-2">Gig benefits</h5><br>
             <p class="content"> {{ gig.gigbenefits}}</p><br>
             <h5 class="left text-body-2">Skills</h5><br>
             <p class="content"> {{ gig.gigskills}}</p><br>
           </v-container>
         </div>
     </div>
   </div>
     <br>

  </v-container>
</template>
<script>
import nativeToast from 'native-toast'
import firebase from '@/plugins/firebase'
let db = firebase.database();
//let usersRef = db.ref('users');
let gigRef = db.ref('gigs');

export default {
  name: 'EditGigs',
  data: () => ({
  authUser: null,
  allGigs: [], // initialise an array
}),
  methods: {
       deleteGigs(gig) {
       (gigRef.child(gig.id).remove())
        console.log("Bamboozle!"+gig.id)
    }
  },
  created: function() {
    //data => console.log(data.user, data.credential.accessToken)
    firebase.auth().onAuthStateChanged(user => {
        if (user) {
          gigRef.child(user.uid).on('child_added', snapshot => {
              this.allGigs.push({...snapshot.val(), id: snapshot.key
              })
              if (snapshot.val().user !== this.authUser) {
                  nativeToast({
                      message: `New message by ${snapshot.val().authUser}`,
                      type: 'success'
                  })
              }
          })
          gigRef.child(user.uid).on('child_removed', snapshot => {
              const deleteGigs = this.allGigs.find(gig => gig.id === snapshot.key)
              const index = this.allGigs.indexOf(deleteGigs)
              this.allGigs.splice(index, 1)
              if (snapshot.val().user !== this.authUser) {
                  nativeToast({
                      message: `Gig deleted by ${snapshot.val().authUser}`,
                      type: 'warning'
                  })
              }
          })
        }
     })
}
}
</script>

错误如下所示:

Console log error saying TypeError: Cannot read properties of undefined (reading 'id')

以下是数据在 firebase 中的显示方式:

Object
z0Dk4aQodPhJk7DwgJZS0kWYAaH2:
-MjxHR5FjvNgB_cvp5Q3: {companydescription: 'nudream is a startup that creates applicacionts fo…siness and upgrades current apps from businesses ', companyname: 'NuDream', gigbenefits: 'Full paid, contract imss, schema mixto alot of benefits, with alot of things ', gigdate: '2021-09-19', gigdescription: 'we are actively looking for an ongoing poisition with strong front end skills!', …}
-MjxUCHolM-AW9pHL_gz: {companydescription: 'Canopy is developing innovative software to suppor… works, what doesn’t, and what could be improved.', companyname: 'Canopy', gigbenefits: 'Competitive salary with opportunities for performa… professional tools you need to do your best work', gigdate: '2021-09-22', gigdescription: 'Our team is growing! We’re seeking to fill several…ur software engineering and client success teams.', …}
-MjxUPZRLRhZ5xglpNAN: {companydescription: 'At GovExec, our mission is to inform and inspire g… in their work and make the world a better place.', companyname: 'Canopy', gigbenefits: 'Competitive salary with opportunities for performa… professional tools you need to do your best work', gigdate: '2021-09-19', gigdescription: 'As the market-leading information platform, for ov…remote work can be accommodated in select states.', …}
-Mjy4Hv3G18t1lZvI2Eq: {companydescription: 'This is the company description, we will see this in a second!', companyname: 'Gigmasters', gigbenefits: 'Lots of benefits!', gigdate: '2021-09-19', gigdescription: 'This is the Gig description!', …}
-Mjy9aKhAPNxNnWriF8K: {companydescription: 'As the market-leading information platform, for ov…s federal, defense, and state and local agencies.', companyname: 'NuStuff', gigbenefits: 'All you want!', gigdate: '2021-09-19', gigdescription: 'As the market-leading information platform, for ov…s federal, defense, and state and local agencies.', …}
-MjzJDQBvPcPgyoLahxN: {companydescription: 'esta es mi company description ', companyname: 'Nudream', gigbenefits: 'alll you want + incentives', gigdate: '2021-09-19', gigdescription: 'esta es mi description de gig ', …}
-Mk0OihUYZv8tQjnb7MS: {companydescription: ' adas dad aas das dasd ', companyname: 'a da da dad asd as d', gigbenefits: ' ada d sadsa dsad sad', gigdate: '2021-09-19', gigdescription: 'a da sdas das d ad sa', …}
[[Prototype]]: Object

这是将数据推送到单独的子组件表单中的方式:

methods: {
        addGig: function() {
            messagesRef.child(this.newGig.userID).push(this.newGig);
            this.newGig.vacanttype = '';
            this.newGig.gigtitle = '';
            this.newGig.gigdescription = '';
            this.newGig.companyname = '';
            this.newGig.companydescription = '';
            this.newGig.giglocation = '';
            this.newGig.gigdate = '';
            this.newGig.gigbenefits = '';
            this.newGig.gigskills = '';
            this.newGig.priority = '';
            toastr.success('Horray! message sent successfully');
            this.displayText = 'Nice job!';
            this.vacanttypeRules = true;
            this.gigtitleRules = true;
            this.gigdescriptionRules = true;
            this.companynameRules = true;
            this.companydescriptionRules = true;
            this.gigskillsRules = true;
            this.gigbenefitsRules = true;
            this.giglocationRules = true;
            this.priorityRules = true;
        },

我想做什么:

Ui look for better understanding I want to delete each object on click

【问题讨论】:

  • 请不要破坏您的帖子。通过在 Stack Exchange 网络上发布,您已根据 CC BY-SA 4.0 许可授予 Stack Exchange 分发该内容的不可撤销的权利(即无论您未来的选择如何)。根据 Stack Exchange 政策,帖子的非破坏版本是分发的版本,因此,任何破坏行为都将被撤销。如果您想了解更多关于删除帖子的信息,请参阅:How does deleting work?

标签: javascript vue.js firebase-realtime-database


【解决方案1】:

你会的

 <div
     // ...
     v-for="gig in allGigs":key="gig._key">
               <div ...>
                 <v-container >
                 <!-- here is my delete button -->
                   <a @click.prevent="deleteGigs(gigs)" href="#" class="card-link"><v-icon color=red>mdi-delete</v-icon></a>
             

但如错误消息所示,gigs 未在v-for 中定义。

你应该这样做:

<a @click.prevent="deleteGigs(gig)"...   //gig without "s"

或者,既然你的deleteGigs()方法如下,

deleteGigs(gigs) {
    gigRef.child(gigs.id).remove()
}

你可以直接通过演出的id,如下:

<a @click.prevent="deleteGigs(gig.id)"...>
//...

deleteGigs(gigsId) {
    gigRef.child(gigsId).remove()
}

【讨论】:

  • @RenaudTarnec 先生感谢您的回答,关于 id 的 id 参考错误已出,我使用了您提到的最后一个选项,我收到参考错误:[Vue warn]: Error in v-在处理程序上:“错误:Reference.child 失败:第一个参数是无效路径 =“未定义”。路径必须是非空字符串,并且不能包含“.”、“#”、“$”、“[”、或“]”“**和第二个错误:** Reference.child 失败:第一个参数是无效路径 =“未定义”。路径必须是非空字符串,并且不能包含“.”、“#”、“$”、“[”或“]”
  • 你应该检查你传递给 child() 方法的所有变量的值。
  • 我该怎么做?
  • 如果我执行 ` 方法:{ deleteGigs(gig) { (gigRef.remove()) console.log(gig) } },` 它会删除 ref 或 ( gigs ) 节点的所有节点然后如果我登录 console.log(gig) 它将抛出我想删除的密钥..所以我不明白它
  • 很多人已经尝试过帮助你。您甚至创建了一个新帐户并再次问了四次相同的问题:stackoverflow.com/users/16999565/whatever。没有得到解决方案。这可能是因为回答者没有得到正确的信息来理解你的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-05
  • 2020-03-06
  • 2021-09-06
  • 2018-12-02
  • 2021-05-29
相关资源
最近更新 更多