2017-09-02 86 views
1

我需要在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。怎么来的?

+2

'saveAction'不返回任何东西。 – str

+0

您需要返回来自电话回复的承诺 – Mikkel

回答

0

功能saveAction不返回任何东西(特别是 - 不返回的承诺),所以你不能在该函数中使用then

export function saveAction(actionInfo){ 
    fetch({ 
    ... 
    }) 
    .then(res => res.json()) 
} 

您可以返回fetch(这是一个承诺)

export function saveAction(actionInfo){ 
    return fetch({ 
    ... 
    }) 
    .then(res => res.json()) 
} 
+0

我认为这很简单!非常感谢! –

-1

如果它可能是像我这样的菜鸟任何帮助,确保returnfetch声明是在同一行,或河畔:然后你就可以在该函数中使用then圆括号中的fetch声明。 避免这个!它也会导致Cannot read property 'then' of undefined错误。

function fetchData(){ 
    return 
     fetch(url) 
     .then(response => response.json()) 
    } 

试试这个。

function fetchData(){ 
    return (
     fetch(url) 
     .then(response => response.json())) 
    } 
+0

与您的问题相关:https://stackoverflow.com/questions/22185128/why-does-the-position-affects-this-javascript-code fetch并不是唯一一个在换行和值之间插入换行符的东西打破。 –

相关问题