尝试设置状态

时间:2018-05-16 15:20:28

标签: reactjs

我尝试上传图片,然后为每个上传的图片设置状态。

但是,在点击“上传”按钮时,我会继续收到此错误消息。按钮:

  

catch:TypeError:无法读取属性' setState'未定义的

此代码块中发生错误:

        .then(function (response) {
            //handle success
            console.log('then: ', response);
            this.setState({
                file: e.target.files[0]
            });
        })

任何帮助将不胜感激! 谢谢!

以下是整个组件:

import React, { Component } from 'react';
import axios from 'axios';

class ImageUpload extends Component {

constructor(props) {
    super(props);
    this.state = { file: '', imagePreviewUrl: '' };
}

_handleSubmit(e) {
    e.preventDefault();
    let fd = new FormData();
    fd.append('image', this.state.file);
    const config = {
        headers: { 'content-type': 'multipart/form-data' }
    }
    const postData = {
        method: 'POST',
        credentials: 'include',
        body: fd
    }

    axios({
        method: 'post',
        url: `/api/gaming/profiles/${this.props.profileId}/files/upload`,
        data: postData
    })
        .then(function (response) {
            //handle success
            console.log('then: ', response);
            this.setState({
                file: event.target.files[0]
            });
        })
        .catch(function (response) {
            //handle error
            console.log('catch: ', response);
        });
}



_handleImageChange(e) {
    e.preventDefault();

    let reader = new FileReader();
    let file = e.target.files[0];

    reader.onloadend = () => {
        this.setState({
            file: file,
            imagePreviewUrl: reader.result
        });
    }

    reader.readAsDataURL(file)
}

render() {
    const { questionId } = this.props;


    let { imagePreviewUrl } = this.state;
    let $imagePreview = null;
    if (imagePreviewUrl) {
        $imagePreview = (<img src={imagePreviewUrl} />);
    } else {
        $imagePreview = (<div className="previewText">Please select an Image for Preview</div>);
    }
    console.log('ImageUpload Render()');
    return (
        <div className="previewComponent">
                <input className="fileInput"
                    type="file"
                    onChange={(e) => this._handleImageChange(e)} />
                <button className="submitButton"
                    type="submit"
                    onClick={(e) => this._handleSubmit(e)}>Upload Image</button>
            <div className="imgPreview">
                {$imagePreview}
            </div>
        </div>
    );
}
}
export default ImageUpload;

2 个答案:

答案 0 :(得分:1)

_handleSubmit(e)定义var self = this 然后使用self.setState代替this.setState

_handleSubmit(e) {
    e.preventDefault();
    let fd = new FormData();
    fd.append('image', this.state.file);
    const config = {
        headers: { 'content-type': 'multipart/form-data' }
    }
    const postData = {
        method: 'POST',
        credentials: 'include',
        body: fd
    }

    var self = this

    axios({
        method: 'post',
        url: `/api/gaming/profiles/${this.props.profileId}/files/upload`,
        data: postData
    })
    .then(function (response) {
        //handle success
        console.log('then: ', response);
        self.setState({
            file: event.target.files[0]
        });
    })
    .catch(function (response) {
        //handle error
        console.log('catch: ', response);
    });
}

答案 1 :(得分:1)

将您的Promise解析器更改为箭头功能,它将为您提供词法范围this

将其更改为:

.then((response) => {
            //handle success
            console.log('then: ', response);
            this.setState({
                file: e.target.files[0]
            });
        })