在React + Redux中批量删除/批量删除

时间:2018-09-25 09:51:28

标签: reactjs react-redux redux-thunk

我有一个允许多个选择和删除功能的数据网格。我有一个从我的api中删除的端点;

DELETE http://localhost:8888/api/audit/id

这是动作创建者;

export function deleteAudit(audits, callback) {
    let count = 0;
    console.log("selected audits", audits);

    const deleteItem = (auditId) => {
        console.log("deleting..", auditId);

        const endpoint = `http://localhost:8888/api/audit/${auditId}`;
        const req = Axios.delete(endpoint, callback);
        return (dispatch) => {
            req.then(res => {
                if (res.status == HttpStatus.OK) {
                    console.log("deleted", auditId);
                    count += 1;
                    if (audits[count] != null) {
                        deleteItem(audits[count]);
                    }
                    else {
                        console.log("all deleted heading to callback");
                        callback();
                    }
                }
            });
            dispatch({type:DELETE_AUDIT, payload: audits});
        }
    }
    deleteItem(audits[count]);
}

由于我的端点一次只允许删除一项,因此我使用了递归函数来连续进行调用。但是,当使用async(thunk)方法进行忽略时,这将无法正常工作,它无法刷新具有新状态的列表。 添加了thunk调度方法后,它只会删除第一个选择,因此我完全迷路了。实现此目标的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

问题是,导入后,我没有导入redux-thunk软件包,正如@Tho Vu在axios上指出的那样,我已如下更改代码;

export const deleteAudit = (audits, callback) => {

    const request = axios.all(_.map(audits, (audit) => 
    {   
        deleteItem(audit);
    }));
    return (dispatch) => {
        request.then(axios.spread((a, f) => {
            dispatch({type:DELETE_AUDIT, payload:audits});
        })).then(() => {
            callback();
        });
    }
}
function deleteItem(id) {
    const endpoint = `http://localhost:8888/api/audit/${id}`;
    return axios.delete(endpoint);
}