【问题标题】:Firebase update callback to detect error and sucssessFirebase 更新回调以检测错误和成功
【发布时间】:2018-12-16 20:51:26
【问题描述】:

如何使这个回调起作用?我已经阅读了文件,但由于某种原因我无法弄清楚?

   var ref = new Firebase("https://xxx.firebaseio.com/public/"+$scope.uid+"/shows/");
var blast = ref.child(show_title);

blast.update({
"show_title": show_title,
"show_image": show_image,
"show_description": show_description,
"show_email": show_email,
"time": Firebase.ServerValue.TIMESTAMP
});

 blast.update("I'm writing data", function(error) {
   if (error) {
    alert("Data could not be saved." + error);
  } else {
    alert("Data saved successfully.");
  }
});

【问题讨论】:

    标签: firebase


    【解决方案1】:

    Frank 的解决方案非常适合您的问题。另一种选择是使用更新承诺。如果您一起执行一堆操作,这在 Firebase 中很常见,这将特别有用。

    这是一个使用承诺的示例

    blast.update({ update: "I'm writing data" }).then(function(){
      alert("Data saved successfully.");
    }).catch(function(error) {
      alert("Data could not be saved." + error);
    });

    【讨论】:

    • 这也确实有效。请注意,当提出问题(我回答)时,Firebase JavaScript SDK did not yet support promises.
    • 在实现 catch() 方法时如何使用setState({...})?每当我尝试使用 this 时,它都是未定义的。
    • @Josh 是作用域的问题。 this 的值取决于函数的调用方式。执行时不能通过赋值来设置,每次调用函数时可能都不一样。您应该在第一级声明const _this = this;,然后在嵌套方​​法中使用_this.setState({})
    【解决方案2】:

    您对update() 的第二次调用会在 JavaScript 控制台中引发此错误:

    未捕获的错误:Firebase.update 失败:第一个参数必须是包含要替换的子对象的对象。(...)

    update 的第一个参数必须是一个对象,所以:

    blast.update({ update: "I'm writing data" }, function(error) {
      if (error) {
        alert("Data could not be saved." + error);
      } else {
        alert("Data saved successfully.");
      }
    });
    

    供参考,这是documentation for the update() function

    【讨论】:

      【解决方案3】:

      在 React ES6 中:

      var refTypes = db.ref("products").child(productId);
      
      var updates = {};
      updates[productId] = newProduct;
      
      refTypes.update(updates).then(()=>{
        console.log("Data saved successfully.");
      }).catch((error)=> {
        console.log("Data could not be saved." + error);
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-03-15
        • 2011-07-25
        • 1970-01-01
        • 2017-01-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多