将Promise.all与React-Redux-Thunk一起使用的更好/正确的方法是什么?

时间:2019-10-10 23:53:33

标签: javascript reactjs redux redux-thunk

export const FETCH_DB_BEGIN = 'FETCH_DB_BEGIN'
export const FETCH_DB_SUCCESS = 'FETCH_DB_SUCCESS'
export const FETCH_DB_FAILURE = 'FETCH_DB_FAILURE'

export const fetchDatabase = () => {
    return dispatch => {
        const profile_url = 'localhost:5000/profiles'
        const release_url = 'localhost:5000/releases'
        const emp_url = 'localhost:5000/users'
        let promises = []

        let options = {
            headers: header,
            method: 'get',
            mode: 'cors',
            body: null,
        }
        dispatch(fetchDbBegin());

        // run the script async. change state when it's done.
        let profile_promise = new Promise((resolve, reject) => {
            fetch(profile_url, options)
                .then(res => res.json())
                .then(resText => {
                    // Use Dispatch Here?
                })
        }).catch(err => {
            console.log(err)
        })
        promises.push(profile_promise)

        // run the script async. change state when it's done.
        let release_promise = new Promise((resolve, reject) => {
            fetch(release_url, options)
                .then(res => res.json())
                .then(resText => {
                })
        }).catch(err => {
            console.log(err)
        })
        promises.push(release_promise)

        // run the script async. change state when it's done.
        let emp_promise = new Promise((resolve, reject) => {
            fetch(emp_url, options)
                .then(res => res.json())
                .then(resText => {

                })
        }).catch(err => {
            console.log(err)
        })
        promises.push(emp_promise)

        Promise.all(promises).then(values => {
            console.log(values)
        })
    }
}

export const fetchDbBegin = () => ({
    type: FETCH_DB_BEGIN
});

export const fetchDbSuccess = (data) => ({
    type: FETCH_DB_SUCCESS,
    payload: { data }
});

export const fetchDbFailure = (err) => ({
    type: FETCH_DB_FAILURE,
    payload: { err }
});

我正在重构一个React类组件以使用Redux。它最初在componentDidMount内部具有所有API调用,而且非常混乱。

我正在使用redux-thunk将其从类组件中移出。

我的fetchDatabase中的databaseAction.js完成了componentDidMount在类组件中所做的一切。

通常,如果它是单个API调用,那么我将在API调用成功完成后调度fetchDbSuccess。但是,使用Promise.All需要进行三个异步API调用,我不确定是否应该

  1. 为每个API调用(fetchProfileSuccessfetchReleaseSuccessfetchUserSuccess)创建一个单独的动作,然后在每个Promise的末尾(我在其中放置{代码中的{1}}。

OR

  1. //Use Dispatch Here?得到解决后,只需调度单个fetchDbSuccess

如果我选择执行2,我应该更新我的reducer中的所有三个Promise.all吗?

谢谢

1 个答案:

答案 0 :(得分:2)

仅当您拥有有关所述状态更新的关心的代码时,才应该调度和更新状态。例如,如果您只想显示单个微调器,然后在完全完成时让微调器消失,则您的用户不一定在乎每个原子操作,因此您不需要将其反映在状态中。如果您有一个确实显示每个UI的UI,则需要这些额外的调度。

顺便说一句,您的Promises看起来有些复杂。如果您决定不需要这些额外的状态更改,则可以简化为:

formatDate