【问题标题】:How to setState in componentDidMount?如何在 componentDidMount 中设置状态?
【发布时间】:2019-06-15 02:58:08
【问题描述】:

在这个项目上工作并尝试调用 firebase 实时数据库信息,然后在调用它后设置一个状态,以便我可以在渲染中使用它。这是我目前的代码,但它的说法 setState 是未知的,我试图阅读这个问题的其他解决方案但不理解它,任何帮助将不胜感激。谢谢。

  componentDidMount(){
    this._getLocationAsync();
    firebase.database().ref('pets/').once('value', function (snapshot) {
        this.setState({ testdid: snapshot.val().name })
     });
  }

【问题讨论】:

标签: reactjs react-native expo setstate


【解决方案1】:

简短的回答是因为您的 firebase 回调中的 this 指的是该函数本身,而不是组件。使用箭头函数应该正确地将this 绑定到组件应该可以修复您的错误:

firebase.database().ref('pets/').once('value', (snapshot) => {
    this.setState({ testdid: snapshot.val().name })
 });

阅读 JS 中的 scope,尤其是关于 this 关键字的内容。一定要知道,因为它有时会有一些奇怪的行为。

【讨论】:

  • @Jayce444 现在将其转换为箭头函数后,这些函数中的关键字“this”是什么?
【解决方案2】:

您的回调是在不同的上下文中进行的,您需要这样做:

 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 })
     }); 
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-21
    • 2018-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-20
    相关资源
    最近更新 更多