React JS - onChange触发两次
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了React JS - 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);
}
有没有办法让它只触发一次?
答案
<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只执行一次。
以上是关于React JS - onChange触发两次的主要内容,如果未能解决你的问题,请参考以下文章