簡體   English   中英

反應本機setState不是函數

[英]React Native setState not a function

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

謝謝

這是lexical scope問題。 使用arrow function

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

發生錯誤的原因是, 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);
         });
 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM