【发布时间】:2020-08-18 13:43:09
【问题描述】:
我从 Firebase 实时数据库中获得了一些数据,现在我正在尝试将其添加到变量中。我确信查询有效,因为如果我 console.log(dataSnapshot) 它记录正确的数据(即 001)。但是,当我尝试使用该数字创建变量时,出现以下错误:Cannot read property 'setState' of undefined 并且它不会向控制台返回任何内容。
这是我的代码:
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);
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);
});
});
Here's the screenshot of my console
提前致谢!
【问题讨论】:
-
您遇到了范围问题:dmitripavlutin.com/javascript-scope
标签: javascript reactjs setstate