简体   繁体   English

React setState不是函数

[英]React setState is not a function

    fileChangedHandler = event => {
    event.preventDefault();
    event.persist();
    new ImageCompressor(event.target.files[0], {
    quality: .6,
    success(result) {
      this.setState({selectedFile: result})
    },
    error(e) {
      console.log(e.message);
    },
  });
  }

That is the function above and I want to change state after success but I'm getting setState is not a function 那是上面的函数,我想在成功后更改状态,但是我得到的setState is not a function

and this is how I trigger it: 这就是我触发它的方式:

<input style={{display: 'none'}} type="file" onChange={this.fileChangedHandler} ref={fileInput => this.fileInput = fileInput}/>
<button type='button' onClick={() => this.fileInput.click()} className='col m3 btn' style={{textTransform: 'none'}}>Choose image</button>

success is regular function that has dynamic this context that is determined by a caller ( ImageCompressor ). success是具有动态正则函数this背景下,由一个呼叫者(确定ImageCompressor )。

Since fileChangedHandler method is an arrow, this refers to component class instance that has setState method. 由于fileChangedHandler方法是一个箭头, this引用具有setState方法的组件类实例。

In order to reach lexical this inside success , it should be an arrow: 为了使词汇表里面this success ,应该是一个箭头:

...
success: (result) => {
  this.setState({selectedFile: result})
},
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM