我的应用程序从 Firebase 实时数据库检索数据并尝试以“状态”加载它,但收到错误“无法读取setState未定义的属性”。
我试图在构造函数中添加绑定,但它不起作用
import React from 'react';
import { View } from '@vkontakte/vkui';
import * as firebase from "firebase/app";
import {config} from './dbinit' // import firebase config
import "firebase/database";
import Home from './panels/Home';
class App extends React.Component {
constructor(props) {
super(props);
this.setState = this.setState.bind(this);
this.state = {
activePanel: 'home',
db: null,
loading: true,
};
console.log("init");
}
componentDidMount = () => {
let ref = firebase
.initializeApp(config)
.database()
.ref();
ref.once("value").then(function onSuccess(res) {
console.log("success", res.val())
this.setState({db: res.val(), loading: false})
// ERROR GOES HERE 'Unhandled Rejection (TypeError): Cannot read property 'setState' of undefined'
});
}
go = (e) => {
this.setState({activePanel: e.currentTarget.dataset.to})
};
render() {
const { loading, db } = this.state;
return loading ? (
<div>loading...</div>
) : (
<View activePanel={this.state.activePanel}>
<div>loaded</div>
</View>
);
}
}
export default App;
我期望正确的工作setState但实际有错误Cannot read property 'setState' of undefined'
红糖糍粑
海绵宝宝撒
相关分类