gpt4 book ai didi

javascript - 使用 axios 配置事件设置状态

转载 作者:行者123 更新时间:2023-11-30 15:35:37 27 4
gpt4 key购买 nike

如何将 Axios 事件结果添加到状态?

  1. 使用axios post方式上传文件
  2. 将状态设置为 axios post metod 的配置 onUploadProgress 事件
  3. 收到以下错误

enter image description here

这是我的代码:

export default class StudioAlbumUpload extends Component{

constructor(props){
super(props);

this.state = { prog: 0 };
}

onDrop(acceptedFiles, rejectedFiles){
var files = acceptedFiles;
var data = new FormData();
data.append('file', files[0]);

var config = {
onUploadProgress: function(progressEvent) {
var percentCompleted = Math.round( (progressEvent.loaded * 100) / progressEvent.total );
//How set state with percentCompleted?
this.setState({prog: percentCompleted});
}
};

axios.post(`${ROOT_URL}/api/studio/album/upload`, data, config)
.then((response) => console.log('hello'))
.catch(error => console.log(error));
}

render() {
return (
<div>
{this.state.prog}
<Dropzone onDrop={this.onDrop} maxSize={5120} accept={'image/*'}>
<div>Try dropping some files here, or click to select files to upload.</div>
</Dropzone>
</div>
);
}
}

最佳答案

箭头函数

您的 onUploadProgress 函数有自己的 this context。但是你需要使用组件的this.setState方法。因此,您最好使用 => arrow function,它没有上下文绑定(bind)并使用之前的 this 上下文。

var config = {
onUploadProgress:(progressEvent) => {
var percentCompleted = Math.round( (progressEvent.loaded * 100) / progressEvent.total );
this.setState({prog: percentCompleted}); //How set state with percentCompleted?
}
};

在这里了解更多关于箭头函数的信息 https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions

更改函数上下文

在此处了解有关绑定(bind)的更多信息 https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/this#The_bind_method

var config = {
onUploadProgress: function(progressEvent) {
var percentCompleted = Math.round( (progressEvent.loaded * 100) / progressEvent.total );
this.setState({prog: percentCompleted}); //How set state with percentCompleted?
}.bind(this)
};

关于javascript - 使用 axios 配置事件设置状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41590386/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com