Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
478 views
in Technique[技术] by (71.8m points)

javascript - 构造函数在异步函数中将此绑定不起作用?(Constructor bind this in async function not working?)

I bind my function in constructor but its return me nothing ?

(我将我的函数绑定到构造函数中,但是什么也没返回?)

what did i do wrong ?

(我做错什么了 ?)

i want to access my class function inside the async function

(我想在异步函数中访问我的类函数)

class UploadAvatar extends React.Component {

    constructor(props) {
      super(props);
      this.changeAvatar = this.changeAvatar.bind(this);
    }

  changeAvatar() {

    console.log('changeavt')


  }
    async function uploadImageAsync(uri) {

      var reader = new FileReader();
      reader.readAsDataURL(blob);
      reader.onloadend = function() {
        var base64data = reader.result;
        // this.changeAvatar(base64data)
        console.log(this)
      }
    }
}
  ask by manyouuwx translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  1. Remove function keyword from your class method.

    (从类方法中删除function关键字。)

  2. Bind your uploadImageAsync with this

    (与此绑定您的uploadImageAsync)

class UploadAvatar extends React.Component {
  constructor(props) {
    super(props);
    this.changeAvatar = this.changeAvatar.bind(this);
    // bind this 
    this.uploadImageAsync = this.uploadImageAsync.bind(this);
  }

  changeAvatar() {
    console.log("changeavt");
  }

  // remove `function` keyword
  async uploadImageAsync(uri) {
    var reader = new FileReader();
    reader.readAsDataURL(blob);
    reader.onloadend = function() {
      var base64data = reader.result;
      // this.changeAvatar(base64data)
      console.log(this);
    };
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...