React 中 Promise 内的 setState

IT技术 javascript reactjs
2021-05-23 16:38:33

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

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

        var response = responseText.json();

        response.then(function(response){
            this.setState({ attachment: response });
        });
    }.bind(this));
}

但是在编译时出现错误,说我在.bind(this). 任何想法,如何在Promise中设置状态?

3个回答

相反,结合this你可以只范围内引用this喜欢

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)