【问题标题】:call function in a fetch promise without this在没有 this 的情况下在 fetch 承诺中调用函数
【发布时间】:2016-12-13 09:21:33
【问题描述】:

我想知道,我该怎么做才能在 fetch 中调用 promise 中的函数?

请注意这一行:.then(json => this.processReq(json))

我必须使用this.,因为如果不是这样,processReq 就是undefined。不应该是这样的:.then(json => processReq(json)) 因为 ES6 吗??

这是我的代码(我正在使用 Babel ES6 和 React):

import React, { Component, PropTypes } from 'react'
import fetch from 'isomorphic-fetch'

export default class Batchprodpry extends Component {
  constructor(props) {
    super(props) {
  .
  .
  .
  processReq(json) {
    Object.keys(json).forEach(item => {
      if (item === 'error') {
        Object.keys(json[item]).forEach(propry => {
          alert('Conflicto! '+'\n'+
            'Id: ' + JSON.stringify(json[item][propry]['propryid'])+'\n'+
            'Id Operador: ' + JSON.stringify(json[item][propry]['fkempid'])+'\n'+
            'Hora inicio: ' + JSON.stringify(json[item][propry]['propryhoraini'])+'\n'+
            'Hora fin: ' + JSON.stringify(json[item][propry]['propryhorafin']))          
        })
      }
    })
  }
  .
  .

  postForm() {
    let maq = this.state.obj['fkmaqid']
    return fetch(`/scamp/index.php/batchprodpry/${maq}`, {
      method: 'POST',
      credentials: 'same-origin',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(this.state.a)
    })
    .then(req => {
      if (req.status >= 400) {
        throw new Error("Bad response from server")
      }
      return req.json()
    })
    .then(json => this.processReq(json))
    .catch(function(error) {
      console.log('request failed', error)
    })
  }

【问题讨论】:

  • "由于 ES6 不应该是 [...] 之类的吗??" - 不,为什么会这样? processReq 仍然是实例的方法。
  • 我更新了我的问题
  • 更新后,processReq 仍然是实例方法,而不是局部变量。局部变量仅使用关键字varlet 声明,您使用ES6 语法如何定义this 引用的方法

标签: reactjs ecmascript-6 fetch-api es6-class


【解决方案1】:

没有。

使用ES6 fat-arrow function 意味着this 绑定到手头函数体以外的其他对象。

如果您使用 ES5 语法来表达类似的函数,this 将绑定到函数体,this.processReq 将未定义:

function (json) {
  return this.processReq(json);  // undefined
}

因此 ES5 等效项必须是:

var self = this;
return fetch(...)
  .then(function (json) {
    return self.processReq(json);
  });

正如在您的特定示例中发生的那样,this 指的是 Batchprodpry 类的实例。 没有名称为processReq的本地函数,只有为类实例定义的方法。

【讨论】:

  • 因为你使用的是 ES6,所以你可以使用this - 在 ES5 中它是没用的
  • 好吧,=> 中使用的词法作用域和function 中使用的动态作用域之间的区别主要在于 this 的绑定 - 请参阅 developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions 以获得良好的文档。与Promise 本身无关,但在执行函数时,闭包变量的值可能已与您认为它们应该是的值不同
  • 什么不起作用?你return 有没有什么或语句应该执行一些副作用而没有?我建议添加一个console.log(variable_of_interest) 然后提出新问题,详细说明什么是“不工作”
  • @RafaelMora:这与承诺无关。 箭头函数在ES6中解决的只是普通的方法调用和回调with the same old problem
  • @RafaelMora:箭头功能不会让this 消失。它改变了它的价值,使其首先发挥作用。使用普通功能,您必须使用thisbind
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-12-05
  • 1970-01-01
  • 2015-11-17
  • 2020-07-08
  • 2023-03-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多