3 回答

TA贡献1815条经验 获得超6个赞
你从不久就失去了上下文。使用的函数:
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'
});
使用箭头函数像这样:
ref.once("value").then((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'
});

TA贡献1809条经验 获得超8个赞
原因是因为您使用的是基于被调用者而不是基于词法范围动态绑定 this 关键字的常规函数......因为这段代码在严格模式下运行(因为它在一个类中)所以 this 关键字被解析作为未定义。
如果您希望保留上下文,您必须绑定函数或使用箭头函数(根据词法范围绑定 this 关键字)
转换这个
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'
});
对此
ref.once("value").then(res => this.setState({db: res.val(), loading: false}));
添加回答
举报