我正在尝试在firebase快照函数中设置状态,但是我收到Cannot read property 'setState' of null
错误。我不确定如何使其发挥作用。
这是我的代码:
componentDidMount = () => {
const dataGoalRef = dbRef.child('goals/'+this.state.uid);
dataGoalRef.child("mainGoal").on("value", function(mainGoalKeySnapshot) {
var favoriteMainGoal = mainGoalKeySnapshot.val();
console.log(favoriteMainGoal);
var queryRef = dataGoalRef.orderByKey().equalTo(favoriteMainGoal);
queryRef.on("value", snap => {
this.setState({
dataGoal: snap.val(),
});
});
});
}
我该怎么办?
答案 0 :(得分:1)
我刚想通了。我没有约束第一种方法。所以解决方案是:
componentDidMount = () => {
const dataGoalRef = dbRef.child('goals/'+this.state.uid);
dataGoalRef.child("mainGoal").on("value", (mainGoalKeySnapshot) => {
var favoriteMainGoal = mainGoalKeySnapshot.val();
console.log(favoriteMainGoal);
var queryRef = dataGoalRef.orderByKey().equalTo(favoriteMainGoal);
queryRef.on("value", snap => {
this.setState({
dataGoal: snap.val(),
});
});
});
}
答案 1 :(得分:0)
尝试使用箭头函数代替普通函数声明进行dataGoalRef.child("mainGoal").on("value", function(mainGoalKeySnapshot){})
中传递的回调
更新代码
dataGoalRef.child("mainGoal").on("value", (mainGoalKeySnapshot) => {
....
....
});