React JS - onChange触发两次

5

当我使用 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) - Julian
@Jin newProfilePicture 是一个箭头函数。不需要绑定。 - Abdul Rauf
@Jin 不需要绑定箭头函数 - Mirakurun
请添加您正在使用的组件的链接,最好附上 [mcve]。您是否在使用 react-images-upload - Abdul Rauf
嗨@AbdulRauf,是的,我正在使用https://www.npmjs.com/package/react-images-upload react-images-upload。 - James Lock
你有没有查看我之前评论中与 react-images-upload 相关的类似问题?那个问题的解决方案在 https://stackoverflow.com/questions/51981376/react-images-upload-how-to-update-state-array-during-onchange 中。 - Abdul Rauf
2个回答

4

如果你正在使用 create-react-app,那么你的 App 组件会被包裹在 StrictMode 中,像这样:

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

前往 index.js 文件并删除 <React.StrictMode></React.StrictMode>

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


当我尝试这个修复方法时,我收到一个错误:event.preventDefault()不是一个函数。 - James Lock
你在<ImageUploader/>中添加了这行代码onChange={event => this.newProfilePicture(event)}吗? - Satyaki
是的,我已经按照你的答案完全理解了。 - James Lock

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接