React JS - onChange触发两次

问题描述 投票:1回答:1

当我使用react-image-uploader上传图像时,onchange会触发两次。所以它试图将图像上传到后端两次,这是我处理它的方式:

//user uploads image to app
<ImageUploader
   buttonClassName={"btn add-btn bg-orange"}
   buttonText='ADD'
   onChange={this.newProfilePicture}
   imgExtension={['.jpg', '.gif', '.png', '.gif']}
   maxFileSize={5242880}
   fileSizeError="file size is too big"
   fileTypeError="this file type is not supported"
   singleImage={true}
   withPreview={true}
   label={""}
   withIcon={false}
/>



 //image is set to this.userprofilepicture
    newProfilePicture = (picture) => {
    this.setState({ userprofilepicture: picture});
    this.setNewProfilePicture();
    ShowAll();
}

//new profilepicture is uploaded to api
setNewProfilePicture = () => {
    let data = new FormData();
    console.log('profile picture: ', this.state.userprofilepicture)
    data.append('Key', 'profilePicture');
    data.append('Value', this.state.userprofilepicture)
    this.sendUpdatedPicture('uploadprofilepicture', data);
}

有没有办法让它只触发一次?

reactjs upload onchange
1个回答
0
投票
<ImageUploader
   buttonClassName={"btn add-btn bg-orange"}
   buttonText='ADD'
   onChange={event => this.newProfilePicture(event)}
   imgExtension={['.jpg', '.gif', '.png', '.gif']}
   maxFileSize={5242880}
   fileSizeError="file size is too big"
   fileTypeError="this file type is not supported"
   singleImage={true}
   withPreview={true}
   label={""}
   withIcon={false}
/>

在功能中,

newProfilePicture = event => {
  event.preventDefault();
  event.stopPropagation();
  ...your code...
}

这应该可以解决您的问题,我们在这里停止将事件传播到下一个级别。这样onChange只执行一次。

© www.soinside.com 2019 - 2024. All rights reserved.