2016-07-19 71 views
-1

我有一個反應類,我從商店
遺漏的類型錯誤:(//某些功能)不是一個函數

class A extends React.component { 
    componentDidMount(){ 
    Store.getData(a).then(data =>{ 
     //some data 
    }); 
    } 

    render(){ 
    //some data 
    } 
} 

而且功能在存儲調用getData功能

getData : function (a) { 
    return (a+b); 
} 

當我運行我得到一個錯誤

Uncaught TypeError: Store.getData(a).then is not a function 我該如何糾正它?

+0

請請勿嘗試使用'
'元素在您的問題中對代碼進行格式化 - 只需正常鍵入,然後使用編輯工具欄上的{}'按鈕將其格式化爲代碼即可。 – nnnnnn

回答

1

功能then用於處理已解決的promises。在您的代碼功能getData中只需返回a+b的結果(即不使用承諾)。如果你想在其他操作中使用then,你應該更新getData函數,以便使用promise,儘管在你的情況下不清楚你爲什麼不能立即使用函數的結果。

這裏是你如何使用承諾:

getData : function (a) { 
    return new Promise(function(resolve, reject){ 
     resolve(a + b); 
    }); 
} 

但是你的函數getData不是異步的,而不是你可以簡單地使用的功能getData結果直接在類的構造函數:

class A extends React.component { 
    componentDidMount() { 
     var yourData = Store.getData(a); 
     // do what you need with this data 
    } 
    // the rest of your class 
} 
+0

注意:第一個片段可以使用['return Promise.resolve(a + b);'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/resolve )。 –

+0

它是一個非常大的代碼,我簡化了它併發布了問題。什麼是其他選項而不是。然後呢?我想使用來自getData方法的數據並進一步使用 – user17422

+0

@JonathanLonowski感謝您的提示,我不知道您可以直接使用'Promise.resolve' – dotnetom

相關問題