2017-09-02 85 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並不是唯一一個在換行和值之間插入換行符的東西打破。 –

相關問題