繁体   English   中英

Redux Thunk 不按顺序分派动作

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM