小编典典

反应本机setState不是函数

reactjs

有人可以解释一下为什么 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);
            });
    }
 }

谢谢


阅读 248

收藏
2020-07-22

共1个答案

小编典典

这是lexical scope问题。使用arrow function

.then((response) => {
    this.setState({ res: response });
})
2020-07-22