React Native setState not a function

◇◆丶佛笑我妖孽 提交于 2019-12-02 00:30:23

This is lexical scope issue. Use arrow function.

.then((response) => {
    this.setState({ res: response });
})

The reason for the error is this does not refer to component class context within resolver function of axios. You can either have resolver function as fat arrow function for your code to work, something like below:

componentDidMount() {
    axios.get('https://api.github.com/repos/torvalds/linux/commits')
        .then((response) => {
            this.setState({res: response});
        }).catch(function(error) {
            console.log(error);
        });
}

or you can change it to something like below:

componentDidMount() {
     let self = this;
     axios.get('https://api.github.com/repos/torvalds/linux/commits')
         .then(function(response) {
             self.setState({res: response});
         }).catch(function(error) {
             console.log(error);
         });
 }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!