2017-05-04 37 views
2

創建我的商店與咚中間件Redux-Thunk「操作必須是普通對象,使用自定義中間件進行異步操作。」

import { createStore, applyMiddleware, compose } from 'redux'; 
import thunk from 'redux-thunk'; 
const store = createStore(
    reducer, 
    initialState, 
    applyMiddleware(thunk) 
); 

,創造我的作用,這要求一個承諾

export function getArticle(url) { 
    return function (dispatch) { 
    fetchArticle(url).then( 
     article => dispatch(setArticle(article)), 
    ); 
    }; 
} 

function fetchArticle(url) { 

    return new Promise((resolve, reject) => { 

    request 
    .get(url) 
    .end((err, res) => { 
     if (err || !res.ok) { 
     reject('Oh no! error'); 
     } else { 
     resolve(res.body); 
     } 
    }); 

    }) 
} 

export function setArticle(article){ 
    return { 
    type: constants.SET_ARTICLE, 
    article 
    } 
} 

在我的文章成分,我呼籲調度上componentDidMount()

componentDidMount(){ 
    this.props.dispatch(
    getArticle('http://api.example.com/') 
); 
} 

但得到錯誤:「操作必須是普通對象,使用自定義中間件進行異步操作。」

這個設置有什麼問題?我曾嘗試致電compose(applyMiddleware(thunk))但無濟於事。

+0

這可能聽起來愚蠢的,但要確保你有終極版,安裝的thunk,'NPM安裝終極版,thunk'。 console.log'thunk'確保存在。 你的代碼看起來很好,它看起來像thunk沒有註冊。 –

回答

0

變化

return function (dispatch) { 
    fetchArticle(url).then( 
     article => dispatch(setArticle(article)), 
    ); 
    }; 

return function (dispatch) { 
    return fetchArticle(url).then( 
     article => dispatch(setArticle(article)), 
    ); 
    }; 
+0

沒有任何區別。仍然得到相同的錯誤。 – Stretch0

0

嘗試以下操作:

export function getArticle(url) { 
    return fetchArticle(url).then( 
     article => dispatch(setArticle(article)), 
    ); 
} 
1

您的代碼看起來不錯,除了它缺少如何處理錯誤(承諾拒絕)。你的API可能會返回錯誤,而你沒有處理它,這可能導致錯誤信息。

嘗試增加

export function getArticle(url) { 
    return function (dispatch) { 
    fetchArticle(url) 
     .then(article => dispatch(setArticle(article))) 
     .catch(err => dispatch({ type: 'SOME_ERROR', err })); 
    }; 
} 
相關問題