繁体   English   中英

清空数组的函数在 then() 中不起作用

[英]function to empty array doesn't work inside then()

以下是我从表单中添加数据的代码,当它捕获this.error的值时,该变量没有给出任何值。 我的代码行有问题吗?

saveContact: async function() {
  this.errors = [];
  if (this.name && this.phone) {
    this.loading = !this.loading;
    await addDoc(collection(db, "users"), {
      id: this.id,
      name: this.name,
      phone: this.phone
    }).then(() => {
      this.name = ""
      this.phone = ""
      // This empty errors not working
      this.errors = [];
    }).catch((error) => {
      this.error = error
    });
  }
  if (!this.name) this.errors.push("name");
  if (!this.phone) this.errors.push("phone");
}

this.error首先用于容纳将要发生的错误,然后如果firebase中的addDoc()函数成功,则then(), this.error = []变量被清空,这样错误消失,但不起作用。

由于您等待承诺,并且在this.phone您正在清除this.namethis.phone - 等待承诺之后的代码将看到this.namethis.phone为空

添加注释以在您的代码中进行解释

saveContact: async function() {
  this.errors = []; // you clear the errors
  if (this.name && this.phone) {
    this.loading = !this.loading;
    await addDoc(collection(db, "users"), {
      id: this.id,
      name: this.name,
      phone: this.phone
    }).then(() => {
      this.name = ""; // you empty the name
      this.phone = ""; // you empty the phone
      // This empty errors not working
      this.errors = []; // you clear the errors for no reason
    }).catch((error) => {
      this.error = error
    });
  }
  // here, name and phone will be empty, because you cleared them in the .then
  if (!this.name) this.errors.push("name");
  if (!this.phone) this.errors.push("phone");
}

一个修复 - else最后一个代码块

saveContact: async function () {
    this.errors = [];
    if (this.name && this.phone) {
        this.loading = !this.loading;
        await addDoc(collection(db, "users"), {
            id: this.id,
            name: this.name,
            phone: this.phone
        }).then(() => {
            this.name = "";
            this.phone = "";
        }).catch((error) => {
            this.error = error
        });
    } else {
        if (!this.name)
            this.errors.push("name");
        if (!this.phone)
            this.errors.push("phone");
    }
}

更好的修复,以及使用 async/await 的更好方法

saveContact: async function () {
    this.errors = []; // you clear the errors
    if (this.name && this.phone) {
        this.loading = !this.loading;
        try {
            await addDoc(collection(db, "users"), {
                id: this.id,
                name: this.name,
                phone: this.phone
            });
            this.name = "";
            this.phone = "";
        } catch {
            this.error = error;
        }
    } else {
        if (!this.name)
            this.errors.push("name");
        if (!this.phone)
            this.errors.push("phone");
    }
}

您可以尝试将“this”存储为某个变量

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM