在handleupload无法读取未定义的属性“ setState”

时间:2018-07-24 07:56:19

标签: javascript reactjs antd

我正在尝试使用antd创建带有fileupload的表单,但是我无法使handleupload函数正常工作,但出现错误:

FileNotFoundError

代码是这样的:

Cannot read property 'setState' of undefined
    at handleupload (registertenantform.js:43)

2 个答案:

答案 0 :(得分:3)

您错过了绑定handleupload函数的权限。只需添加

this.handleupload = this.handleupload.bind(this)

在您的RegisterTenantForm构造函数中

您可以使用箭头函数重写handleupload函数,如下所示:

handleupload = (info) => {
  //let files = e.target.files;
  if (info.file.status === 'uploading') {
    this.setState({ loading: true });
    return;
  }

  if (info.file.status === 'done') {
    // btw you dont need two separated setState here, you can do
    // it in one setState
    this.setState({
      'selectedFiles': info.file,
      loading: false
    });
  }
}

答案 1 :(得分:1)

您的this正在处理promise中的局部范围,因为setState方法应该是未定义的,因此您需要将其分配给另一个变量,如下所示:

const that = this;

,并可以在下面的承诺代码中访问它:

adalApiFetch(fetch, "/Tenant", options)
  .then(response => response.json())
  .then(responseJson => {
    if (!that.isCancelled) {
      that.setState({
        data: responseJson
      });
    }
  })
  .catch(error => {
    console.error(error);
  });