如何正确实现进度条?

How to implement progress bar properly?

所以我在 React 和 ChakraUI 上做这个项目来显示图像。我的要求是每当有人上传图片时显示进度条。 我的问题是,当我重新加载页面时,进度条第一次工作正常,例如我 select 一张图片,在 select 下载图片后,我按下上传按钮并显示进度条。只有第一次它工作正常。在那之后,每当我只是 select 图像时,进度条就已经满了。之后,单击上传按钮即可上传。 如何防止这种情况发生?

import * as React from "react";

import { Button, Flex, Progress } from "@chakra-ui/react";
import { useState } from "react";
import axios from "axios";

import { baseUrl } from "../config";

function Upload(props) {
  const [selectedFile, setSelectedFile] = useState(null);
  const [curretFile, setCurrentFile] = useState(null);
  const [progress, setProgress] = useState(0);
  const [error, setError] = useState(null);

  function fileSelectedHandler(event) {
    setSelectedFile(event.target.files[0]);
  }

  const fileUploadHandler = (event) => {
    const fd = new FormData();
    fd.append("image", selectedFile, selectedFile.name);

    axios
      .post(`${baseUrl}/upload`, fd, {
        headers: {
          "Content-Type": "multipart/form-data",
        },
        onUploadProgress: (event) => {
          setProgress(Math.round((100 * event.loaded) / event.total));
        },
      })
      .then((res) => {
        props.onSuccessfulUpload();
        setSelectedFile(null);
        setError(null);
      })
      .catch((error) => {
        setSelectedFile(null);
        setError(error);
      });
  };

  const fileData = () => {
    if (selectedFile) {
      if (
        selectedFile.type === "image/jpeg" ||
        selectedFile.type === "image/png"
      ) {
        return (
          <div>
            {error && <div>file too large!!</div>}
            <Button colorScheme='teal' size='sm' onClick={fileUploadHandler}>
              Upload!
            </Button>
            <Progress value={progress} min='0' max='100' width='40' />
          </div>
        );
      } else {
        return (
          <div>
            <h4>Please choose an image to upload</h4>
          </div>
        );
      }
    } else {
      return (
        <div>
          <h4>Choose Photos</h4>
        </div>
      );
    }
  };

  return (
    <div>
      <input type='file' onChange={fileSelectedHandler} />
      {fileData()}
    </div>
  );
}

export default Upload;

忘记把进度状态设置为0了,感谢老哥提醒把进度设置为0

  .then((res) => {
        props.onSuccessfulUpload();
        setSelectedFile(null);
        setError(null);
        setProgress(0); //setProgress to zero
      })