没有这个的获取承诺中的调用函数

Raf*_*ora 2 ecmascript-6 reactjs fetch-api es6-class

我想知道,我该怎么做才能在获取中以诺言方式调用函数?

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

我不得不用this.,因为如果没有它说,processRequndefined。应该不是这样的:.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)
    })
  }
Run Code Online (Sandbox Code Playgroud)

Apr*_*ion 5

没有。

使用ES6粗箭头功能意味着this可以绑定到除当前功能主体以外的其他位置。

如果您使用ES5语法表示类似的功能,this则将绑定到功能主体,并且this.processReq将无法定义:

function (json) {
  return this.processReq(json);  // undefined
}
Run Code Online (Sandbox Code Playgroud)

因此,等效于ES5的必须是:

var self = this;
return fetch(...)
  .then(function (json) {
    return self.processReq(json);
  });
Run Code Online (Sandbox Code Playgroud)

在您的特定示例中,它this是指Batchprodpry类的实例。没有名称processReqlocal的局部函数,只有为类实例定义的方法。

  • @RafaelMora:箭头功能不会使“ this”消失。它会更改其值以使其首先起作用。使用正常功能,您必须使用`this`和`bind`! (2认同)