[英]Redux Thunk Not Dispatching Actions in Order
我正在使用 redux thunk,但遇到以下問題。 uploadClientImage
調度創建一個圖像對象到數據庫並返回圖像 id。
在創建 client_info 之前,我需要 2 個圖像 ID。
問題是在我從 2 個uploadClientImage
調度中檢索 id 之前調用了 axios post to clients
在調用 axios post 請求之前,有沒有辦法等到這 2 個調度完成?
動作.js
export function uploadClientImage(image_file) {
return function(dispatch) {
var formData = new FormData();
for (var key in image_file) {
formData.append(key, image_file[key]);
}
console.log(formData);
axios.post(`${API_URL}/photos`, formData, {withCredentials: true, headers: {'Content-Type': 'multipart/form-data'}})
.then(response => {
var image_id = response.data.id;
return image_id;
})
.catch(() => {
console.log("Can't fileUpload");
});
}
}
export function createClient(client_info, logo, photo) {
return function(dispatch) {
var logo = client_info.logo_id[0];
var logo_id= dispatch(uploadClientImage(logo);
var photo = client_info.photo_id[0];
var photo_id = dispatch(uploadClientImage(photo));
client_info["photo_id"] = photo_id;
client_info["logo_id"] = logo_id;
axios.post(`${API_URL}/clients`, client_info, {withCredentials: true})
.then(response => {
//......
})
.catch(() => {
console.log("Can't create client");
});
}
}
我不認為uploadClientImage
需要是一個 redux 操作,因為你沒有調度任何東西。 它應該只是一個返回承諾的常規函數。 我稍微重構了你的代碼(沒有測試)。
export function uploadClientImage(image_file) {
var formData = new FormData();
for (var key in image_file) {
formData.append(key, image_file[key]);
}
console.log(formData);
// return the promise axios creates
return axios.post(`${API_URL}/photos`, formData, {withCredentials: true, headers: {'Content-Type': 'multipart/form-data'}})
.then(response => {
var image_id = response.data.id;
return image_id;
})
.catch(() => {
console.log("Can't fileUpload");
});
}
export function createClient(client_info, logo, photo) {
return function(dispatch) {
var logo = client_info.logo_id[0];
var photo = client_info.photo_id[0];
// upload both images at the same time, continue when both are done
Promise.all([uploadClientImage(logo), uploadClientImage(photo)])
.then(function(results){
client_info["photo_id"] = results[0];
client_info["logo_id"] = results[1];
return axios.post(`${API_URL}/clients`, client_info, {withCredentials: true})
})
.then(response => {
//......
})
.catch(() => {
console.log("Can't create client");
});
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.