我需要在API上发布一些内容。 我有这个功能,正常工作:React Promise:TypeError:无法读取未定义的属性'then'
TradeContainer.js:
callApi(action){
var actionInfo = {
user_id: this.props.currentUser.id,
action: action
}
fetch('http://localhost:3000/actions', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(actionInfo)
})
.then(res => res.json())
.then(data => console.log(data))
}
我想从那里我让所有的API调用移动取()到另一个文件。在那个文件中,我已经有了几个获取函数(使用get方法),它们工作正常。 但是,当我提出这个取()的方法后该文件,我得到一个错误:
TypeError: Cannot read property 'then' of undefined
我的代码:
TradeContainer.js:
import { saveAction } from '../components/apiCalls.js'
callApi(action){
var actionInfo = {
user_id: this.props.currentUser.id,
action: action
}
//this is fetch() function that i moved to apiCalls.js file.
//And this two lines of code throw an error.
saveAction(actionInfo)
.then(data => console.log(data))
}
apiCalls.js
export function saveAction(actionInfo){
fetch('http://localhost:3000/actions', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(actionInfo)
})
.then(res => res.json())
}
。然后(res => res.json())返回“ok”和200. 但是saveAction(actionInfo)返回undefined。怎么来的?
'saveAction'不返回任何东西。 – str
您需要返回来自电话回复的承诺 – Mikkel