使用Redux-Thunk / Axios从onUploadProgress事件调度操作

时间:2018-03-28 15:44:14

标签: reactjs react-redux axios redux-thunk

以下代码上传文件没有问题并成功响应或失败,但是,我无法弄清楚如何从uploadFileProgress事件发送onUploadProgress操作。我可以console.log进度/百分比,当我尝试将调度包装在IIFE中时,我触发调度不是函数错误。希望这是一个我错过的小问题。提前谢谢!

export function uploadFile(values, callback = () => {}) {
  const uploadFileData = new FormData();
  uploadFileData.append('fileName', values.fileName);
  uploadFileData.append('file', values.file);
  uploadFileData.append('file', {
    filename: values.filename,
    contentType: values.contentType,
  });
  const uploadProgress = {
    onUploadProgress: (ProgressEvent) => {
      let progressData = 0;
      const totalLength = ProgressEvent.lengthComputable ? ProgressEvent.total : ProgressEvent.target.getResponseHeader('content-length') || ProgressEvent.target.getResponseHeader('x-decompressed-content-length');
      if (totalLength !== null) {
        progressData = Math.round((ProgressEvent.loaded * 100) / totalLength);
      }
      return function action(dispatch) {
        dispatch(uploadFileUpload(progressData));
      };
    },
  };
  const configPlusProgress = Object.assign(uploadProgress, config);
  const request = () => axios.post(myURL, uploadFileData, configPlusProgress);
  return function action(dispatch) {
    dispatch(uploadFileLoading(true));
    return request()
      .then((response) => {
        if (response.status !== 201) {
          dispatch(uploadFileFail());
          throw Error(response.statusText);
        }
        dispatch(uploadFileLoading(false));
        return response;
      })
      .then(response => dispatch(uploadFileSuccess(response)))
      .then(() => callback())
      .catch(err => dispatch(uploadFileFail(err)));
  };
}

3 个答案:

答案 0 :(得分:3)

在返回的函数内移动您的请求配置(可以访问dispatch函数):

export function uploadFile(values, callback = () => {}) {
  const uploadFileData = new FormData();
  uploadFileData.append('fileName', values.fileName);
  uploadFileData.append('file', values.file);
  uploadFileData.append('file', {
    filename: values.filename,
    contentType: values.contentType,
  });
  return function action(dispatch) {
    const uploadProgress = {
      onUploadProgress: (ProgressEvent) => {
        let progressData = 0;
        const totalLength = ProgressEvent.lengthComputable ? ProgressEvent.total : ProgressEvent.target.getResponseHeader('content-length') || ProgressEvent.target.getResponseHeader('x-decompressed-content-length');
        if (totalLength !== null) {
          progressData = Math.round((ProgressEvent.loaded * 100) / totalLength);
        }

        dispatch(uploadFileUpload(progressData));
      },
    };
    const configPlusProgress = Object.assign(uploadProgress, config);
    const request = () => axios.post(myURL, uploadFileData, configPlusProgress);

    dispatch(uploadFileLoading(true));
    return request()
      .then((response) => {
        if (response.status !== 201) {
          dispatch(uploadFileFail());
          throw Error(response.statusText);
        }
        dispatch(uploadFileLoading(false));
        return response;
      })
      .then(response => dispatch(uploadFileSuccess(response)))
      .then(() => callback())
      .catch(err => dispatch(uploadFileFail(err)));
  };
}

同样onUploadProgress应该只是上传进度事件。

答案 1 :(得分:0)

我无法完全修复你的代码,但这里是一个基本的函数,使用redux-thunk执行异步操作和使用操作。

const doSomeAsyncStuff = () =>
    async ( dispatch ) => {
         try {
             const response = await someAsyncStuff();
             return dispatch( someSuccessAction( response.data );
         } catch ( error ) {
             return dispatch( someFailureAction( err );
         }
    }

当然必须将redux-thunk添加为中间件。

答案 2 :(得分:0)

为什么要从onUploadProgress函数返回一个函数

return function action(dispatch) {
    dispatch(uploadFileUpload(progressData));
  };

而不是你可以

dispatch(uploadFileUpload(progressData));