首页 > 解决方案 > this.setState() on react native 不使用文本输入

问题描述

我正在尝试将用户的信息从 firebase 打印到 TextInput 的占位符中,但是当我尝试设置它没有表示的信息时,节点给了我一条消息:

错误:

 Please update the following components: ProfileContent
 LOG  user logged
 LOG  -----O myemail.com
 LOG  -----O myname
 LOG  -----O mylastname
 LOG  -----O adriangc24
 WARN  Possible Unhandled Promise Rejection (id: 1):
TypeError: undefined is not an object (evaluating '_this2.setState')

我的构造函数:

constructor(props) {
    super(props);
    this.state = {
      name: "",
      lastname: "",
      displayname: "",
      email: "",
    };
  }
  state = {
    name: "Nombre",
    lastname: "Apellidos",
    displayname: "Nombre de usuario",
    email: "Correo electrónico",
  };

文本输入示例:

    <TextInput
                      autoCapitalize="sentences"
                      style={styles.userInput}
                      placeholder={this.state.lastname}
                      ref={"lastnamesInput"}
                    />

我从 firebase 获取用户数据的方法:

function getUserData() {
  firebase.auth().onAuthStateChanged(function (user) {
    if (user) {
      console.log("user logged");
      var usuario = firebase.database().ref("/users/" + user.uid);
      usuario.once("value").then((snapshot) => {
        var usr = snapshot.val();
        console.log("-----O " + usr.email);
        console.log("-----O " + usr.name);
        console.log("-----O " + usr.lastname);
        console.log("-----O " + usr.displayname);

        this.setState(
          {
            name: usr.name,
            lastname: usr.lastname,
            displayname: usr.displayname,
            email: usr.email,
          },
          () => {
            console.log("///////////////////////////////////////");
            console.log("XXXXXX " + this.state.email);
          }
        );
      });
    } else {
      console.log("user not logged");
    }
  });
}

标签: reactjsfirebasereact-nativefirebase-realtime-databasefirebase-authentication

解决方案


这是范围问题,由于function (user) {您失去了范围this,解决方案是使用fat arrow function

改变这个:

  firebase.auth().onAuthStateChanged(function (user) {

  firebase.auth().onAuthStateChanged((user) => {

推荐阅读