How to use fetch() API in React to setState

前端 未结 5 1434
孤街浪徒
孤街浪徒 2020-12-08 23:19

I\'m trying to write a component in React that will use the fetch() API to get data from a website, then use setState to set a state equal to the data, and then finally rend

5条回答
  •  一生所求
    2020-12-09 00:11

    It is saying setState is undefined because you're accessing it in the wrong context. You can either, convert the function into an arrow function or bind it to the right context. Here is an article as to When and why do we bind this to the React component method.

    In your code, the change that can be made is either binding it

    .then(function(jsonStr){
              this.setState({apiInfo: jsonStr});
              console.log(jsonStr);
          }.bind(this));
    

    or using arrow function

    .then((jsonStr)=>{
              this.setState({apiInfo: jsonStr});
              console.log(jsonStr);
          });
    

提交回复
热议问题