如何在本地反应axios.get?

问题描述 投票:0回答:1

我是新来的本地人。我正在尝试做axios.get()。但是我在控制台中得到这个:

        serverData: serverData
      })', '_this.setState' is undefined)]

_this.setState is not a function. (In '_this.setState({
    serverData: serverData
  })', '_this.setState' is undefined)

这是我的代码:

state = {
    serverData: [],
};

axios.get('http://api.myslambook.in/swagger/#/users/', {
    auth: {
        username: 'xxxx',
        password: 'xxxxx'
    }
    }).then(res => {
        const serverData = res.data;
        this.setState({serverData});
    }).catch(err => console.log(err));

有人可以帮忙吗?谢谢。

react-native axios swagger-ui
1个回答
0
投票

嘿,您可以通过以下方法处理axios

承诺方式

componentDidMount(){
    axios.get('http://api.myslambook.in/swagger/#/users/', {
        auth: {
            username: 'xxxx',
            password: 'xxxxx'
        }
    }).then(res => {
        this.setState({
            serverData: res.data.serverData
        });
    }).catch(err => console.log(err));
}

异步/等待方法

async componentDidMount(){
    try {
        let response = await axios.get('http://api.myslambook.in/swagger/#/users/', {
            auth: {
                username: 'xxxx',
                password: 'xxxxx'
            }
        })
        this.setState({
            serverData: response.data.serverData
        });
    } catch (error) {
        console.log(error)
    }
}

希望这对您有所帮助。随时提出疑问。

© www.soinside.com 2019 - 2024. All rights reserved.