功能无法设定的状态

时间:2020-09-15 21:53:03

标签: reactjs react-native state setstate

无法设置状态

我正在尝试将我的状态randomUserDataName设置为从其他函数检索的randomUser.Name 但是无法从我的getRandomUser函数中获取状态数据

function getRandomUser() {
  var ref = firebase.database().ref("users");
  ref.limitToLast(1).on(
    //"value",
    "child_added",
    function (snapshot) {
      () => console.log("after this log is current user's data");
      var randomUser = snapshot.val();
      var randomUserDataName = randomUser.Name;
      var randomUserDataLastName = randomUser.LastName;
      var randomUserDataAge = randomUser.Age;
      var randomUserDataBio = randomUser.Bio;
      console.log(randomUserDataName);
      console.log(randomUserDataAge);
    },
    function (errorObject) {
      console.log("The read failed: " + errorObject.code);
    }
  );
}

这里是获取用户的数据功能

class HomeScreen extends Component {
  constructor(props) {
    super(props);
    this.state = {
      randomUserDataName: "",
      randomUserDataLastName: "",
      randomUserDataBio: "",
      randomUserDataAge: "",
      randomUserDataInstagram: "",
      currentuserUID: "",
    };
  }

## here the my class's state

1 个答案:

答案 0 :(得分:1)

您必须使用setState。请更好地研究一下文档:

https://reactjs.org/docs/react-component.html#setstate