setState inside Promise in React



我的 React 代码中有一个函数,定义如下:

getAttachment(url) {
    fetch(url).then((responseText) => {
        var response = responseText.json();
        response.then(function(response){
            this.setState({ attachment: response });
        });
    }.bind(this));
}

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

而不是绑定this,你可以只将引用范围限定为this .

like
var that = this;

然后引用that.setState .

这是因为函数内部有不同的作用域。使用函数时,它有自己的作用域。而"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>;
     }

}

尝试将getAttachment函数更改为 getAttachment = (url) => {...}和删除.bind(this)

最新更新