简体   繁体   English

React:如何更改变量的 state?

[英]React: How to change the state of a variable?

I've queried some data from Firebase realtime database and now I'm trying to add it to a variable.我从 Firebase 实时数据库中查询了一些数据,现在我正在尝试将其添加到变量中。 I'm sure that the querying works, because if I console.log(dataSnapshot) it logs the correct data (which is 001).我确信查询有效,因为如果我 console.log(dataSnapshot) 它记录正确的数据(即 001)。 However, when I'm trying to create a variable out of that number it doesn't return anything.但是,当我尝试使用该数字创建变量时,它不会返回任何内容。

Here is a part of my code:这是我的代码的一部分:

class Table extends Component {
  constructor(props) {
    super(props);
    this.state = { timestamps: [], user: auth().currentUser, serial: "" };
  }

  componentDidMount() {
    const uid = this.state.user.uid;
    console.log(uid);
    const serial = this.state.serial;
    const serialRef = db.ref(uid + "/serial");
    serialRef.once("value").then(function (dataSnapshot) {
      console.log(dataSnapshot.val());
      this.setState({ serial: dataSnapshot.val() });
    });
    console.log(serial);

Here is a screenshot of my console这是我的控制台的屏幕截图

Thanks in advance!提前致谢!

This is happening because you are logging your state variable serial to the console before its value is getting changed(asynchronous behaviour).发生这种情况是因为您正在将 state 变量串行记录到控制台,然后再更改其值(异步行为)。 Hence you are getting your serial variable as the original one.因此,您将串行变量作为原始变量。
If you wish to console.log your state variable serial in another variable immediately after setState then do the following:如果您希望在 setState 之后立即在另一个变量中控制台记录您的 state 变量序列,请执行以下操作:

componentDidMount() {
    const uid = this.state.user.uid;
    console.log(uid);
    let serial = this.state.serial;
    const serialRef = db.ref(uid + "/serial");
    serialRef.once("value").then(function (dataSnapshot) {
      console.log(dataSnapshot.val());
      this.setState({ serial: dataSnapshot.val() }, () => {
          serial = this.state.serial 
          console.log(serial)
        });
      });
    })
}

setState accepts a callback as an optional second parameter. setState 接受回调作为可选的第二个参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM