【发布时间】:2017-03-27 12:43:08
【问题描述】:
我遇到了 redux thunk 流程的问题。
在动作创建器中,我首先创建一个图像对象并从数据库中获取image_id。
我有一个名为clients 的变量,它是需要图像ID 的所有客户端ID 的列表。 [1,2,3,4,5]
我通过一个 for 循环,使用 axios.get 获取客户端,并将新的 image_id 添加到来自客户端字段的图像列表中。
然后我将新的更改放在现场的客户client_images。
export function addNewClient(imageData, clients) {
return function(dispatch) {
axios.post(`${API_URL}/media`, fileData, { withCredentials: true, headers: { 'Content-Type': 'multipart/form-data' } })
.then(response => {
var image_id = response.data.id;
//go through each client to get current background list
for (var i = 0; i < clients.length; i++) {
var currRow = clients[i];
console.log("GETTING NEW CLIENT", currRow)
axios.get(`${API_URL}/clients/${currRow}`, { withCredentials: true })
.then(response => {
var currImages = response.data.client_images;
var clientImages = [...currImages, image_id];
console.log("ADDING NEW CLIENT IMAGE IDs", currRow);
axios.put(`${API_URL}/clients/${currRow}`, {client_images:clientImages}, { withCredentials: true })
})
.catch(() => {
console.log("Can't set image list to clients");
});
}
});
}
}
我的问题出在这里: 整个 for 循环在我调用之前就完成了
axios.put(`${API_URL}/clients/${currRow}`, {client_images:clientImages}, { withCredentials: true })
在我的控制台中,这是输出
如您所见,添加新客户端图像仅在 for 循环完成后调用。我需要在 for 循环内调用“添加新客户端图像”,以便可以调用其他 axios 函数,而不是向 id 为 5 的客户端调用 5 次。
有没有办法让 for 循环在 redux thunk 中工作?
【问题讨论】:
标签: reactjs asynchronous redux-thunk