如何从React Native中的componentDidMount中的函数访问this.state?

时间:2017-12-07 21:21:58

标签: reactjs react-native

当我尝试在this.state内的函数中使用它时,

componentDidMount未定义。 this指的是componentDidMount中的组件,但不是从嵌套函数调用它时。我试过将它绑定到函数但没有运气。我正在使用React Native,但我相信这一般适用于React。这是componentDidMount

componentDidMount(){
    console.log(this.state); //is state of the Component
    //this.state.foos is an array
    var foosRef = firebase.database().ref('foos');
    foosRef.on('child_added', function(child){
      console.log(this.state); //is undefined
      this.setState((prevState) => {
        return {foos: prevState.push(child) }
      })

    }).bind(this)

  }

我目前在构造函数中有以下内容:

this.componentDidMount.bind(this);

我还尝试在回调结束时绑定this,而不是.on之后绑定TypeError: prevState.push is not a function. (In 'prevState.push(child)', prevState.push is undefined) ,但这也不起作用。

错误是:

state

this不是prevState的属性。

我知道你不应该改变this.state.foos.push(child) ,但我以前做过

{{1}}

并且没有查找添加元素作为原始副本的语法。

1 个答案:

答案 0 :(得分:3)

问题是你的处理函数中'this'的上下文不是你组件的定义。您可以通过以下三种方式之一解决此问题:

  1. 在调用foosRef.on之前,添加

    let my = this;
    
  2. 然后在内联处理程序函数中引用“my”而不是“this”。

    OR, 2.将内联处理程序函数移动到组件类的独立成员,例如:

    function foosRefOnHandler(child){
      console.log(this.state); //is undefined
      this.setState((prevState) => {
        return {foos: prevState.push(child) }
      }
    

    然后,您必须更改foosRef.on调用以绑定该方法:

    foosRef.on('child_added', this.foosRefOnHandler.bind(this));
    

    OR, 3.使用内联箭头函数而不是处理程序,例如:

    foosRef.on('child_added', (child) => {
      console.log(this.state); //is undefined
      this.setState((prevState) => {
        return {foos: prevState.push(child) }
      })
    
    })