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