React native get实时数据库数据不起作用(firebase)?

时间:2017-08-07 12:19:17

标签: reactjs react-native

我是反应原生的新手,并尝试使用firebase作为后端构建一个简单的应用程序。

我已经注册,登录,注销并设置了移动电话号码。我试图实时读取移动数据数据。获取数据的功能如下:

    _listenForMobileNumberChanges(userId, callback) {

    let userMobilePath = "/user/" + userId + "/details";

    firebase.database().ref(userMobilePath).on('value', (snapshot) => {

        var mobile = "";

        if (snapshot.val()) {
            mobile = snapshot.val().mobile
        }

        callback(mobile)
      });
    }

在渲染函数中,我放置了一个ListView并调用了函数:

<ListView
        dataSource={this.state.mobile}
        renderRow={() => {this._listenForMobileNumberChanges(this.state.userId}}
     />

我知道我在Listview调用中缺少回调参数,但我不知道要添加到参数中的内容,是否有人可以提供帮助?

1 个答案:

答案 0 :(得分:1)

而不是使用Listview而不是使用TextInput而在TextInput的onChangeText属性中调用metode,如下所示:

    <TextInput
      style={{height: 40, borderColor: 'gray', borderWidth: 1}}
      onChangeText={(usermobileNumber) => this._listenForMobileNumberChanges()}
      value={this.state.usermobileNumber}
    />

解析没有参数只需将方法修改为:

_listenForMobileNumberChanges() {
    alert('inside the listen function');

    if(firebase.auth().currentUser) {
      let userId = firebase.auth().currentUser.uid;
      let userMobilePath = "/user/" + userId + "/details";

      firebase.database().ref(userMobilePath).on('value', (snapshot) => {

          var mobile = "";

          if (snapshot.val()) {
              mobile = snapshot.val().mobile
          }

          this.setState ({usermobileNumber: mobile});
      });
    } else {
      this.setState ({usermobileNumber: ''});
    }
  }