Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
230 views
in Technique[技术] by (71.8m points)

javascript - Couldn't setState from the then function of the Promise

I'm trying to update the state from the promise which I received using the fetch function.

componentDidMount(){

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

     var response = responseText.json();

     response.then(function(response){
         this.setState(response);
     });

  });
}

I was getting the error that the setState is not an function

Then, I tried to bind(this) to pass the this value like below.

componentDidMount(){

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

     var response = responseText.json();

     response.then(function(response){
         this.setState(response);
     });

  }).bind(this);
}

It is not working now also. Same error again.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is because of the scoping of this, so you're on to something when you're trying to use Function.prototype.bind. Your mistake is that you don't bind all the way down to the last anonymous function. What you probably want to do is use arrow functions all the way, like this:

componentDidMount(){
    fetch(url)
        .then((responseText) => responseText.json())
        .then((response) => this.setState(response));
}

Arrow functions always keep the context of this.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...