在Redux中,替换动作创建者中的dispatch

时间:2017-03-30 14:02:14

标签: reactjs redux dispatch

鉴于我的行动创造者:

export const REQUEST_ARTICLES = 'REQUEST_ARTICLES'
export const RECEIVE_ARTICLES = 'RECEIVE_ARTICLES'
export const CHANGE_PAGE = 'CHANGE_PAGE'

export const changePage = (currentPage) => ({
    type: CHANGE_PAGE,
    currentPage,
})

export const requestArticles = () => ({
    type: REQUEST_ARTICLES,
})

export const receiveArticles = json => ({
    type: RECEIVE_ARTICLES,
    posts: json.hits,
})

export const fetchArticles = () => async (dispatch) => {
    try {
        await dispatch(requestArticles())
        let response = await fetch('www.abc.com')
        let json = await response.json()
        await dispatch(receiveArticles(json))
    } catch (e) {
        console.log('error:', e)
    }
}

所以我在动作创建者中使用调度。但如果我必须分派多个动作,那么我的代码就是

        try {
            await dispatch(requestArticles1())
            await dispatch(requestArticles2())
            await dispatch(requestArticles3())
            await dispatch(requestArticles4())
            await dispatch(requestArticles5())
            let response = await fetch('www.abc.com')
            let json = await response.json()
            await dispatch(receiveArticles(json))
        } catch (e) {
            console.log('error:', e)
        }

我已在组件中使用mapDispatchToProps。我是否可以在动作创建者中使用任何类似的方法/方法,以便我不必逐个手动发送动作?

1 个答案:

答案 0 :(得分:1)

redux的store.dispatch()不是异步函数,因此不需要await返回它。它仍然有效,因为await非异步函数将它们转换为立即解决的承诺。

关于调度多个操作,您需要手动调度所需的每个操作。问题变成:你为什么需要派出这么多行动?通常,对于ajax调用thunk,您将使用启动,成功和失败的操作,而不是更多。

export const fetchArticles = () => async (dispatch) => {
    try {
        dispatch(requestArticlesStarted())
        const response = await fetch('www.abc.com')
        const json = await response.json()
        dispatch(requestArticlesSucceeded(json))
    } catch (e) {
        console.log('error:', e);
        dispatch(requestArticlesFailed(e));
    }
}