使用 axios 配置事件设置状态

Set state with axios config event

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

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

这是我的代码:

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 上下文 。但是你需要使用components 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)
};