如何将Axios事件结果添加到州?
onUploadProgress
事件
这是我的代码:
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>
);
}
}
答案 0 :(得分:2)
箭头功能
您的onUploadProgress
函数有自己的this
上下文。但是您需要使用组件this.setState
方法。因此,您最好使用=>
箭头函数,它没有上下文绑定并使用之前的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
更改功能背景
了解有关此处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)
};