【问题标题】:ReactJS - access this.props within a promiseReactJS - 在 Promise 中访问 this.props
【发布时间】:2018-04-10 17:13:47
【问题描述】:

我有一个返回承诺的静态方法:

static getInfo(ID)
 { return new Promise((resolve, reject) => {   
    api.getList(ID)
      .then((List) => {
        resolve(Info);
      })
      .catch((error) => {
        // here I need to access this.props which is undefined
        console.log(this.props);

      });
     .catch(reject);
   });
 }

this.props 是承诺中的undefined。我怎样才能访问它?

【问题讨论】:

  • 您正在尝试以静态方法访问this
  • this 的作用域是 promise 而不是 this.props try var self = this 在调用方法之前
  • @FadiAboMsalam:不,上面的函数是箭头函数。 (和this != "scope")

标签: javascript reactjs promise


【解决方案1】:

正如对该问题的评论中所述,您在静态方法中使用this,根据定义,该方法与实例无关(因此,this 不会指向组件实例)。

您可以:

  1. 通过删除 static 使其成为实例方法
  2. 或者,将道具/组件实例作为参数传递给方法。

    static getInfo(ID,props){...}

    Component.getInfo(ID, this.props) //In your component where this.props is available

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-11
    • 2018-04-03
    • 2018-09-20
    • 2015-04-11
    • 1970-01-01
    • 1970-01-01
    • 2019-07-17
    • 2016-08-04
    相关资源
    最近更新 更多