[英]Unstated Cannot read property 'setState' of undefined
I'm using a state library called unstated and when I run the following code: 我正在使用一个名为unstated的状态库,并且在运行以下代码时:
import { Container } from 'unstated';
import Fire from '../Core/Fire';
class Store extends Container {
state = {
users: [],
};
getAllUsers() {
const db = Fire.firestore();
const reference = db.collection('users');
reference
.get()
.then(snapshot => {
const docs = [];
snapshot.forEach(doc => {
docs.push(doc);
});
this.setState({
users: docs.map(doc => {
return {
id: doc.id,
model: doc.data(),
};
}),
});
})
.catch(error => {
console.error(error);
});
}
}
export default Store;
I get this error: 我收到此错误:
TypeError: Cannot read property 'setState' of undefined at Store.js:19 TypeError:无法读取Store.js上未定义的属性“ setState”:19
I'm definitely getting results back as docs
does contain objects at the time I want to set the state. 我肯定会得到结果,因为docs
在我想要设置状态时确实包含对象。 I'm also doing things exactly the same way they are in their documentation / example. 我做的事情也与文档/示例中的做事完全相同。
Why isn't the reference this
seen? 为什么不参考this
见过? Is it because it's in a promise? 是因为承诺吗? Doh! 卫生署!
You should either bind the function or use arrow function. 您应该绑定功能或使用箭头功能。
1.) 1.)
constructor(){
this.getAllUsers=this.getAllUsers.bind(this)
}
2) 2)
getAllUsers = () =>{ ... }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.