当我使用 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);
}
有没有办法只让它触发一次?
newProfilePicture
吗? 像这样:this.newProfilePicture = this.newProfilePicture.bind(this)
- JuliannewProfilePicture
是一个箭头函数。不需要绑定。 - Abdul Raufreact-images-upload
相关的类似问题?那个问题的解决方案在 https://stackoverflow.com/questions/51981376/react-images-upload-how-to-update-state-array-during-onchange 中。 - Abdul Rauf