2017-05-04 122 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 })); 
    }; 
} 
相关问题