简体   繁体   中英

How to fix scope problem inside “then” function react?

I am trying to print out of Printer. I am a little new to react and javascript. I am trying to pass the state to a then function of Third Party Code. But i am getting an error:

Cannot read property 'restaurant_name' of undefined

How can i pass state to the scope of then function of qz ?

print = () => {
    let { state } = this.state;
    qz.websocket.connect()
    .then(function() {
     return qz.printers.find("BillPrinter");
   }).then(function(printer) {
         var config = qz.configs.create(printer);
         var data = [
              `${state.restaurant_name}` + '\x0A',
              `${state.restaurant_address}`
         ]

         return qz.print(config, data);
    });
}

You have some unnecessary destructuring that is causing your error - this.state.state doesn't exist, yet this line:

let { state } = this.state;

Is equivalent to:

let state = this.state.state;

Remove the curly braces and it'll work fine.

let state = this.state;

Also note that state will be a reference to this.state rather than being another object.

使用箭头函数将函数保留在上限范围内,如@Ali Torki建议的那样:

.then(printer => {....})

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