【发布时间】:2019-06-24 16:59:35
【问题描述】:
我的应用从 Firebase 实时数据库中检索数据并尝试以“状态”加载它,但出现错误“无法读取属性 setState of undefined”。
我尝试在构造函数中添加绑定,但它不起作用
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'
【问题讨论】:
-
考虑阅读这个:freecodecamp.org/news/…
-
这不是在自定义组件类方法中丢失
this,而是由于回调function而丢失上下文。一个快速的解决方法是将var appThis = this;放在ref.once()调用之前,然后在回调中使用appThis.setState(...);。
标签: javascript reactjs