我需要在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