Trying to implement a SIMPLE promise in Reactjs

后端 未结 2 875
野性不改
野性不改 2021-02-04 13:36

Just trying out Promises for the first time in React. I have a basic promise working (ripped from someone else\'s code), but don\'t know how to adapt it to be useful.

Wh

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-04 14:13

    You need to be thinking about the scope you're in. When you are in the function you're passing to promise.then, you are in a new block scope and therefore any var you create in the function won't exist outside of it's scope. I'm not sure how you're defining your React components, but assuming you have a newName variable on your component, there are two ways you could solve the scope problem - bind and arrow functions:

    promise.then(function(result) {
      this.newName = result; //or what you want to assign it to
    }.bind(this))
    

    and then you could reference it using {this.newName}

    Or with an arrow function:

    promise.then((result) => {
      this.newName = result; //or what you want to assign it to
    }.bind(this))
    

    I would recommend watching this egghead video to help you understand the this keyword in javascript.

提交回复
热议问题