我希望将上传的文件数量限制为10个,如果数量仅超过10个,则会显示一条错误消息.但是,如果我try 一次上传11个文件,我的屏幕上会出现11次错误信息.

const beforeUpload = (file,fileList) => {
        const maxFileSize = 250 * 1024 * 1024; // 250MB limit
        const maxLimit = 10
        if (fileList.length>maxLimit){
            message.error(`Only 10 files allowed`);
            return false;
        }

        if (file.size > maxFileSize) {
            message.error(`${file.name} file upload failed (exceeds 250MB)`);
            console.error("File size exceeds the limit of 250MB");
            return false;
        }
        return true;
    };

我试着在bepreUpload中处理它,但如果它超过10个文件,我可以禁用文件上传.但是,我一次都不能显示该消息.如果我try 上传11个文件,它会显示11次.关于如何显示一次消息并限制文件上传,有什么 idea 吗?

<Upload.Dragger multiple beforeUpload={beforeUpload} customRequest={handleFileUpload} showUploadlist={false}>...</Upload.Dragger>

推荐答案

限制一次上传文件数量的最简单方法是使用max countprops ,但在这种情况下,你不会通知你的用户.

如果您需要通知用户,您可以使用ref来控制您是否已将此错误通知给用户:

const notificated = useRef(false)
function beforeUpload(file){
  const index = fileList.indexOf(file);
  const maxLimit = 10
  if (fileList.length > maxLimit){
    if (!notificated.current) {
      notificated.current = true;
      message.error(`Only 10 files allowed`);
    }

    if (index === fileList.lenght - 1) {
      // reached last upload item
      // we must reset notification status now
      notificated.current = false;
    }

    return false;
  }

  const maxFileSize = 250 * 1024 * 1024; // 250MB limit
  if (file.size > maxFileSize) {
    message.error(`${file.name} file upload failed (exceeds 250MB)`);
    console.error("File size exceeds the limit of 250MB");
    return false;
  }
  return true;
};

您还可以找到一个有效的示例here

Reactjs相关问答推荐

从`redux—thunk`导入thunk `在stackblitz中不起作用

404使用GitHub操作部署Next.js应用程序时出错

cypress 不能点击SPAN

使用Overpass API Endpoint计算 map 上的面积

将对象添加到集合中的数组时的no_id字段

UseEffect和useSelector的奇怪问题导致无限循环

使用筛选器的Primereact DataTable服务器端分页?

不同步渲染

获取更改后的状态值

React Todo List 应用程序我在实现删除功能时遇到问题

UseEffect 似乎不适用于页面的首次渲染

画布:用鼠标绘制形状时重新绘制整个画布会导致卡顿

为什么 createSlice 中的 reducer 不能以不同的方式改变状态?

在 React JS 中编辑表格数据

页面加载时不显示数组中的数据

有没有办法根据 Rechart 中的 activeDot 更改值?

React Native PermissionsAndroid 不包括 READ_MEDIA_IMAGES.如何解决这个问题?

如何使用react 路由将 url 参数限制为一组特定的值?

如何在 React 中的 Material Ui 多选中设置默认值?

Rtk 查询无效标签不使数据无效