React JS - onChange 触发两次

IT技术 reactjs upload onchange
2021-05-16 21:09:43

当我使用 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个回答

如果您正在使用,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

<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 只执行一次。