React JS-onChange触发两次

时间:2018-11-26 11:26:10

标签: reactjs upload onchange

当我使用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);
}

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

2 个答案:

答案 0 :(得分:4)

如果您使用的是create-react-app,则您的App组件将像这样包装在StrictMode中:

<React.StrictMode>
  <App />
</React.StrictMode>,

转到 index.js 并删除<React.StrictMode></React.StrictMode>

https://github.com/facebook/react/issues/12856#issuecomment-390206425

答案 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仅执行一次。