React中的Promise中的setState

typ*_*pos 2 javascript reactjs

我在我的React代码中有一个函数,如下所示:

getAttachment(url) {
    fetch(url).then((responseText) => {

        var response = responseText.json();

        response.then(function(response){
            this.setState({ attachment: response });
        });
    }.bind(this));
}
Run Code Online (Sandbox Code Playgroud)

但是当我编译时我得到一个错误,说我有一个意外的令牌.bind(this).任何想法,如何在承诺中设置状态?

kti*_*lcu 8

而不是绑定this你可以只是范围引用this.喜欢

var that = this;
Run Code Online (Sandbox Code Playgroud)

然后参考that.setState.


Sha*_*ana 6

这是因为您在函数内部有不同的作用域。使用函数时,它有自己的作用域。与函数外使用的“this”在函数内使用时不一样。最好的方法是拥有一个变量“that”并将之前的“this”分配给“that”。

class Hello extends React.Component {
    constructor(props) {
        super(props);
        this.getAttachment = this.getAttachment.bind(this);
        this.state = {attachmenet: ""};
    }

    getAttachment(url) {

         //Code you need to add
         var that = this;

         fetch(url).then((responseText) => {

            var response = responseText.json();

            response.then(function(response){
               //code you need to change
               that.setState({ attachment: response });
            });
         });
     }

     render() {
         this.getAttachment();
         return <div dangerouslySetInnerHTML={{__html:this.state.attachment}}>
       </div>;
     }


}
Run Code Online (Sandbox Code Playgroud)