我需要在我的 API 上发布一些内容。 我有这个功能可以正常工作:
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))
}
我想将 fetch() 移动到另一个文件,我从那里进行所有 API 调用。在那个文件中,我已经有几个获取函数(使用 get 方法)并且它们工作正常。 但是当我将这个带有 post 方法的 fetch() 移动到那个文件时,我得到一个错误:
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())
}
.then(res => res.json()) 返回“ok”和 200。 但是 saveAction(actionInfo) 返回 undefined。怎么会?
最佳答案
saveAction
函数不返回任何内容(特别是 - 不返回 promise),因此您不能在该函数上使用 then
:
export function saveAction(actionInfo){
fetch({
...
})
.then(res => res.json())
}
您可以返回 fetch
(这是一个 promise ),然后您可以在该函数上使用 then
:
export function saveAction(actionInfo){
return fetch({
...
})
.then(res => res.json())
}
关于javascript - react promise : TypeError: Cannot read property 'then' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46014667/