【问题标题】:How to access 'this' keyword inside of static method in react native?如何在本机反应中访问静态方法内的“this”关键字?
【发布时间】:2018-11-21 08:34:44
【问题描述】:

我无法在 react-native 的静态方法中访问“this”关键字,当我尝试访问它时,它会抛出类似“this.setState not a function”这样的错误。

这是我的代码。

static getShiftStatus = () =>{
        //for check shift start or not  
        Usermodal.getShiftStatus((isStatus) =>{
            this.setState({isShiftStart: isStatus}) //error occure here.
            console.log(a.state.isShiftStart)
        }) 
    }

【问题讨论】:

  • 静态方法不会在类的实例上调用,因此如果您只删除 static 关键字,它应该可以按预期工作。
  • 在构造函数中将方法绑定到实例?

标签: javascript android ios reactjs react-native


【解决方案1】:

this 在内部函数中指向别的东西。 您需要从外部函数中捕获this

static getShiftStatus = () =>{

        var that = this;  // capture here

        Usermodal.getShiftStatus((isStatus) =>{
            that.setState({isShiftStart: isStatus})  // use it here
            console.log(a.state.isShiftStart)
        }) 
    }

【讨论】:

  • 但是内部函数是箭头函数,所以它不使用其包含上下文中的this值吗?
  • 这个不能在静态函数下使用
猜你喜欢
  • 2021-02-05
  • 1970-01-01
  • 2021-05-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-21
  • 2014-04-12
相关资源
最近更新 更多