3

我想知道,我该怎么做才能在 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)
    })
  }
4

1 回答 1

6

不。

使用ES6 fat-arrow 函数意味着它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类的实例。没有name 的本地函数processReq,只有为类实例定义的方法。

于 2016-08-07T14:30:22.070 回答