繁体   English   中英

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

[英]How to access this.state from a function inside componentDidMount in React Native?

当我尝试在componentDidMount的函数内使用this.state时,它是未定义的。 this是指componentDidMount中的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)

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

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

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

     let my = this; 

然后在内联处理程序函数中引用“ my”,而不是“ this”。

或者,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));

或3.使用内联箭头函数代替处理程序,例如:

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

})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM