Реагируйте на Native setState, а не на функцию - PullRequest
0 голосов
/ 29 июня 2018

Может кто-нибудь объяснить мне, почему this.setState не является функцией?

Я не понимаю, почему в моем коде ошибка

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);
            });
    }
 }

Спасибо

Ответы [ 2 ]

0 голосов
/ 29 июня 2018

Причина ошибки: this не относится к контексту класса компонента в функции распознавателя axios. Вы можете использовать функцию распознавателя в качестве жирной стрелки для вашего кода, как показано ниже:

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

или вы можете изменить его на что-то вроде ниже:

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);
         });
 }
0 голосов
/ 29 июня 2018

Это lexical scope проблема. Используйте arrow function.

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