首页 > 解决方案 > React Dropzone 组件 - 如何动态更改 postUrl?

问题描述

我正在使用 react dropzone 组件https://github.com/felixrieseberg/React-Dropzone-Component来促进将文件拖放到站点上。

我希望每个拖放到 dropzone 上的文件都发布到不同的 url(AWS Pre-Signed URL)。本质上,我希望组件配置参数“postUrl”随着这个预签名 URL 的变化而动态变化。

我目前有以下组件配置集

class Uploader extends React.Component {
  constructor(props){
   super(props);
   this.dropzone = 'null'
  }

  config = () => (
    {
      iconFiletypes: ['.jpg', '.png', '.gif'],
      showFiletypeIcon: true,
      postUrl: this.dropzone.options.url || 'no-url'
    }
  );

  eventHandlers = () => (
    {
      processing: function(file) {
      },
      init: dz => this.dropzone = dz,
    }
  );

  djsConfig = (requestID=this.props.requestId) => (
    {
      addRemoveLinks: false,
      acceptedFiles: "image/jpeg,image/png,image/gif",
      autoProcessQueue: true,
      init: function () {
        this.on("processing", async (file) => {
          const presigned_url = await uploadUrl(file, requestID, () => {})
          this.options.url = presigned_url;
        });
      }
    }
  );
}

加载页面/组件时出现以下错误:

Uncaught TypeError: Cannot read property 'url' of undefined

在处理文件时更新options.urlDropzone 对象djsConfig没有机会postUrl: this.dropzone.options.url按我的意愿更新?

标签: javascriptreactjs

解决方案


As commented by lex. Change your init method as below:

     init:function () {
         var _this=this;
         this.on("processing", async (file) => {
            const presigned_url = await uploadUrl(file, requestID, () => {})
           _this.options.url = presigned_url;
        });
     }

推荐阅读