简体   繁体   中英

how to correctly setState in the reactjs function

In my case, I want to change the image url to base64 file using the "base64-img" library.

I intend to save the results of converting the file into a state. I tried saving it to a variable also failed. I wrote the script as follows:

var base64Img = require('base64-img');
base64Img.requestBase64('url_image', function(err, res, body) {
  this.setState ({ b64:body });
});

I get an error Uncaught TypeError: Cannot read property 'setState' of undefined

I try to set the value to a variable then console_log works well, but the value cannot be accessed from outside.

let b64;
base64Img.requestBase64('url_image', function(err, res, body) {
  b64 = body;
  console.log(b64);
});

I want to use the value b64 outside of the function. Thanks

You can use ES6 arrow function to call setState and to access b64 outside the function or in custom function, you can bind the function inside the constructor and access using this

const base64Img = require('base64-img');
//convert image to base 64
convertImgtoBase64(imageUrl) {
    base64Img.requestBase64(imageUrl,(err, res, body) => {
       this.setState ({ b64:body });
    });
}

Like this

constructor(props){
    super(props);
    this.state = {
        b64: null
    };
    this.convertImgtoBase64 = this.convertImgtoBase64.bind(this);
    this.showBase64Value = this.showBase64Value.bind(this);
   }
   showBase64Value(){
      console.log(this.state.b64);
   }

You used

var base64Img = require('base64-img');
base64Img.requestBase64('url_image', function(err, res, body) {
  this.setState ({ b64:body });
});

Here this will indicate the function instance, so that that instance won't contain setState method

So I suggest to try to use like this

var base64Img = require('base64-img');
let _self = this;
base64Img.requestBase64('url_image', function(err, res, body) {
  _self.setState ({ b64:body });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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