Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Can someone explain me why this.setState is not a function ?

I do not see why my code has an error

import React from 'react';
import axios from 'axios'
import { StyleSheet, Text, View , Image} from 'react-native';

export default class App extends React.Component {

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

Thank you

See Question&Answers more detail:os

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

1 Answer

This is lexical scope issue. Use arrow function.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...