React JS - onChange 触发两次 [英] React JS - onChange triggering twice

查看:153
本文介绍了React JS - onChange 触发两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用 react-image-uploader 上传图片时,onchange 会触发两次.所以它尝试将图像上传到后端两次,这是我的处理方式:

When I upload an image using react-image-uploader the onchange triggers twice. so it attempts to upload the image to the backend twice, here is how I handle it:

//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);
}

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

Is there a way to get this to only trigger once?

推荐答案

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

if you are using create-react-app then your Appcomponent is wrapped in StrictMode like this:

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

转到 index.js 并删除

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

这篇关于React JS - onChange 触发两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆