在 React 和 Redux 中上传多张图片

Uploading Multiple Images in React and Redux

我正在尝试上传多张图片,我正在将图片一张一张地传递给 API 因此,一旦图片上传完毕,它就可以显示,而无需等待其他图片完成正在上传。

我的问题是我有一个加载器,我在上传图片时显示它。如果有的图片已经上传完了,有的还在上传,加载器已经消失了?

组件

{
  isImagesUploading && (
    <Box sx={{ width: "100%" }}>
      <LinearProgress />
    </Box>
  );
}



const onUploadImage = (files) => {
  const fileList = Array.from(files);
  const images = fileList.map((image) => {
    ...
  });

  uploadImages(newImages);
};

减速器

case UPLOAD_IMAGES_REQUEST:
      return {
        ...state,
        isImagesUploading: true,
      }
case UPLOAD_IMAGES_REQUEST:
      return {
        ...state,
        isImagesUploading: false,
        images: action.payload
      }

动作

export const uploadImages =
  ({ images }) =>
  async (dispatch) => {
    images.forEach(async (image) => {
      const formData = new FormData();
      formData.append(image.name, image.imageFile);

      try {
        dispatch({
          type: UPLOAD_IMAGES_REQUEST,
        });

        const response = await axios.post("http://test.com", formData);

        dispatch({
          type: UPLOAD_IMAGES_SUCCESS,
          payload: [...(images || [])],
        });
      } catch (error) {
        dispatch({
          type: UPLOAD_IMAGES_FAILURE,
        });
      }
    });
  };

您可以跟踪待处理上传的计数。任何大于 0 的计数都会显示 UI 中的任何加载指示器。

示例:

case UPLOAD_IMAGES_REQUEST:
  return {
    ...state,
    imageUploadCount: state.imageUploadCount + 1,

case UPLOAD_IMAGES_REQUEST:
  return {
    ...state,
    imageUploadCount: state.imageUploadCount - 1,
    images: action.payload
  };

case UPLOAD_IMAGES_FAILURE:
  return {
    ...state,
    imageUploadCount: state.imageUploadCount - 1,
  };

...

export const uploadImages = ({ images }) => (dispatch) => {
  images.forEach(async (image) => {
    const formData = new FormData();
    formData.append(image.name, image.imageFile);

    try {
      dispatch({ type: UPLOAD_IMAGES_REQUEST });

      const response = await axios.post("http://test.com", formData);

      dispatch({
        type: UPLOAD_IMAGES_SUCCESS,
        payload: [...(images || [])],
      });
    } catch (error) {
      dispatch({ type: UPLOAD_IMAGES_FAILURE });
    }
  });
};

在您的 ui 中,创建一个状态选择器函数来读取计数并确定是否应显示任何加载指示器。

示例:

const isUploading = useSelector(state => state.images.imageUploadCount > 0);

...

return (
  <>
    {isUploading && <LoadingSpinner />}
    ...
  </>
);