簡體   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