在react-redux-promise app

时间:2016-06-30 11:56:41

标签: javascript reactjs redux reducers redux-promise

我的应用程序的数据源仅提供XML格式的数据。

我使用axios来获取XML数据。它最终作为结果的数据部分中的字符串。

我曾尝试使用xml2js进行转换,但它只是触发异步作业并返回,所以我不会让redux-promise middelware工作。当reducer将数据发送到应该呈现它的组件时,有效负载是没有的。

不确定这是否有意义,但是我可以让reducer等待新函数调用返回之前在组件上发送数据吗?

动作index.js

export function fetchData(jobid, dest) {
    const url = `${DATA_URL}jobid=${jobid}&refdist=${dest}`;
    const request = axios.get(url);

    console.log(request);

    return {
        type: FETCH_DATA,
        payload: request
    }
}

我的减速机

export default function (state = [], action) {
    console.log(action);

    switch (action.type) {
        case FETCH_DATA:
            console.log("pre");
            parseString(action.payload.data, function (err, result) {
                // Do I need some magic here??? or somewhere else?
                console.dir(result);
            });

        return [action.payload.data, ...state];
    }
    return state;
}

1 个答案:

答案 0 :(得分:3)

你应该更改你的动作创建者代码,因为axios是异步的。并在收到数据后发送动作。 您在reducer中不需要这个逻辑。 对于异步操作,您可以使用redux-thunk

export const fetchData = (jobid, dest)=>dispatch =>{
    const url = `${DATA_URL}jobid=${jobid}&refdist=${dest}`;

    const request = axios.get(url).then(res=>{
        parseString(res, function (err, result) {
           if(result){
                dispatch({
                   type: FETCH_DATA,
                   data:result
                })
            }
            if(err) throw err
        });
    }).catch(err=>console.error(error))

};
///clean reducer
export default function (state = [], action) {
     switch (action.type) {
        case FETCH_DATA:
        return [...state, action.data ];
    }
    return state;
}

此外,您可能需要了解提取过程:加载,成功,失败。然后,动作创建者可能看起来像:

export const fetchData = (jobid, dest)=>dispatch =>{
 const url = `${DATA_URL}jobid=${jobid}&refdist=${dest}`;
    dispatch({
       type: FETCH_DATA_REQUEST,
       data:result,
       isFetching:true
    })
    const request = axios.get(url).then(res=>{
        parseString(res, function (err, result) {
           if(result){
                dispatch({
                   type: FETCH_DATA_SUCCESS,
                   data:result,
                   isFetching:false
                })
            }
            if(err) throw err
        });
    }).catch(err=>{
        dispatch({
           type: FETCH_DATA_FAILURE,
           err:err,
           isFetching:false
        })
        console.error(error)
    })

};