如何在 componentDidMount 中设置状态?
How to setState in componentDidMount?
在这个项目上工作并尝试调用 firebase 实时数据库信息,然后在调用它之后设置一个状态,以便我可以在渲染中使用它。这是我目前的代码,但它说 setState 是未知的,我试图阅读这个问题的其他解决方案,但不明白,任何帮助将不胜感激。谢谢
componentDidMount(){
this._getLocationAsync();
firebase.database().ref('pets/').once('value', function (snapshot) {
this.setState({ testdid: snapshot.val().name })
});
}
简短的回答是因为 this
在你的 firebase 回调中指的是函数本身,而不是组件。使用箭头函数应该正确地将 this
绑定到组件应该修复你的错误:
firebase.database().ref('pets/').once('value', (snapshot) => {
this.setState({ testdid: snapshot.val().name })
});
阅读 JS 中的 scope,特别是关于 this
关键字的内容。知道这一点绝对重要,因为它有时会有一些奇怪的行为。
您的回调是在不同的上下文中进行的,您需要做的是:
componentDidMount(){
this._getLocationAsync();
firebase.database().ref('pets/').once('value', function (snapshot) {
this.setState({ testdid: snapshot.val().name })
}.bind(this)); // bind to current context
}
或者我更喜欢 ES6
componentDidMount(){
this._getLocationAsync();
firebase.database().ref('pets/').once('value', snapshot => { // Using Fat Arrow
this.setState({ testdid: snapshot.val().name })
});
}
在这个项目上工作并尝试调用 firebase 实时数据库信息,然后在调用它之后设置一个状态,以便我可以在渲染中使用它。这是我目前的代码,但它说 setState 是未知的,我试图阅读这个问题的其他解决方案,但不明白,任何帮助将不胜感激。谢谢
componentDidMount(){
this._getLocationAsync();
firebase.database().ref('pets/').once('value', function (snapshot) {
this.setState({ testdid: snapshot.val().name })
});
}
简短的回答是因为 this
在你的 firebase 回调中指的是函数本身,而不是组件。使用箭头函数应该正确地将 this
绑定到组件应该修复你的错误:
firebase.database().ref('pets/').once('value', (snapshot) => {
this.setState({ testdid: snapshot.val().name })
});
阅读 JS 中的 scope,特别是关于 this
关键字的内容。知道这一点绝对重要,因为它有时会有一些奇怪的行为。
您的回调是在不同的上下文中进行的,您需要做的是:
componentDidMount(){
this._getLocationAsync();
firebase.database().ref('pets/').once('value', function (snapshot) {
this.setState({ testdid: snapshot.val().name })
}.bind(this)); // bind to current context
}
或者我更喜欢 ES6
componentDidMount(){
this._getLocationAsync();
firebase.database().ref('pets/').once('value', snapshot => { // Using Fat Arrow
this.setState({ testdid: snapshot.val().name })
});
}