使用 Redux-Thunk / Axios 从 onUploadProgress 事件分派动作

IT技术 reactjs react-redux axios redux-thunk
2021-05-16 01:09:52

以下代码上传文件没有问题,并按预期成功或失败响应,但是,我无法弄清楚如何uploadFileProgressonUploadProgress事件中分派我的操作我可以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个回答

将您的请求配置移动到返回的函数中(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应该只是dipatch上传进度事件。

我不能完全修复您的代码,但这里有一个基本功能,redux-thunk 执行异步操作并使用操作。

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

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

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

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

取而代之的是,你可以

dispatch(uploadFileUpload(progressData));