在组件用我从Firebase提取的数据挂载(在cmoponentWillMount中)之前,我正在尝试对组件进行setState,但是我收到了一个错误:“无法读取未定义的属性'setState‘。如何正确设置状态,以便组件装载正确的数据?”
componentWillMount(){
const rootRef = fire.database().ref('groups')
rootRef.limitToFirst(1).once('value', function(snap) {
snap.forEach(function(child){
var first = (child.val()).id;
console.log(first);
this.setState({ selectedGroupId: first });
})
});
}发布于 2018-10-23 16:57:43
尝尝这个。
不要在循环中执行setState,因为您使用的是常规函数,所以请将其更改为箭头函数,如下所示。还切换到componentDidMount方法,因为不推荐componentWillMount
componentDidMount(){
const rootRef = fire.database().ref('groups')
rootRef.limitToFirst(1).once('value', snap => {
let first = 0;
snap.forEach(child => {
first = (child.val()).id;
console.log(first);
})
this.setState({ selectedGroupId: first });
});
}如果您不喜欢使用箭头函数,也可以这样绑定它
componentDidMount(){
const rootRef = fire.database().ref('groups')
rootRef.limitToFirst(1).once('value', function(snap) {
let first = 0;
snap.forEach(function(child){
first = (child.val()).id;
console.log(first);
}.bind(this));
this.setState({ selectedGroupId: first });
}.bind(this));
}开始使用let & const而不是var。
发布于 2018-10-23 16:48:55
这是因为这个的作用域是未定义的。您需要使用ES6箭头函数传递它。
componentWillMount(){
const rootRef = fire.database().ref('groups')
rootRef.limitToFirst(1).once('value', (snap) => {
snap.forEach((child) => {
var first = (child.val()).id;
console.log(first);
this.setState({ selectedGroupId: first });
})
});
}这边试试。
https://stackoverflow.com/questions/52953897
复制相似问题