How to use fetch() API in React to setState

前端 未结 5 1445
孤街浪徒
孤街浪徒 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:15

    • this refers to the object which calls the function.
    • every normal function has its own this however arrow functions does not (this here refers to the outside context i.e., what this is outside the function.).

    So the possible solutions are

    • Use Arrow function
    componentDidMount = () => {
        fetch('https://fcctop100.herokuapp.com/api/fccusers/top/recent').then(
                function(response){
                    return response.json();
                }
                ).then(function(jsonData){
                    return JSON.stringify(jsonData);
                }
                ).then(function(jsonStr){
                    this.setState({apiInfo: jsonStr});
                    console.log(jsonStr);
                });
    }
    
    • save this in some other variable earlier and pass it as argument.
    • Bind this to the function

    https://reactjs.org/docs/handling-events.html

提交回复
热议问题