【问题标题】:I cannot retrieve the username from firebase我无法从 firebase 检索用户名
【发布时间】:2017-03-06 04:27:18
【问题描述】:

我目前正在尝试以 react native 从 firebase 数据库返回用户名。 console.log 在函数内部工作,但不记录函数外部的任何内容。我不知道我哪里错了。这是我的代码。

  componentWillMount() {
    firebase.database().ref('/users/' + this.userId + '/username').once('value').then(function(snapshot) {
    this.username = snapshot.val();
    console.log(this.username)
    });
    console.log(this.username)
    this.setState({
      username: this.username
    })
  }  

【问题讨论】:

标签: javascript firebase react-native firebase-realtime-database


【解决方案1】:

由于某种原因,将语法更改为 es6 的箭头函数使得代码与在函数内添加 this.setState 一起工作

componentWillMount() {
    firebase.database().ref('/users/' + this.userId + '/username').once('value').then((snapshot) => {
    this.username = snapshot.val();
    console.log(this.username)
    this.setState({
      username: this.username
    })
  })
  }

【讨论】:

    【解决方案2】:

    这是因为 JavaScript 的异步特性。您应该在回调中执行setState

    firebase.database().ref('/users/' + this.userId + '/username').once('value').then(snapshot => {
        this.username = snapshot.val();
        console.log(this.username);
        this.setState({
          username: this.username
        })
    });
    

    【讨论】:

    • 可能未处理的 Promise Rejection
    • 如您所见,使用箭头函数进行回调。它会在回调中自动绑定this。更新了我的答案。
    猜你喜欢
    • 1970-01-01
    • 2019-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多