axios 不能使用,而 fetch 可以

axios does not work with while fetch does

我想从 /{url} 获取数据(数组),我尝试了这段代码

// Fetch the list on first mount
componentDidMount() {
this.getList();
}

// Retrieves the list of items from the Express app
getList = () => {

fetch('/main')
.then(res => res.json())
.then(list => this.setState({ list }))
}

这工作正常,但后来我决定切换到 axios 并尝试使用完全相同的代码

  // Fetch the list on first mount
componentDidMount() {
this.getList();
}

 // Retrieves the list of items from the Express app
 getList = () => {
 axios.get('/main')
.then(res=> res.json())
.then(list => this.setState({list}))

}

但它没有用,并在这一行给我错误:.then(res=> res.json()) 所以我不知道有什么问题如果有人知道线索如果你告诉我我会很高兴

这是因为 axios 有不同的响应,而不是 res.json() return 数据已经像:return res.data 或直接将它传递给状态

getList = () => {
 axios.get('/main')
   .then(res=> this.setState({list: res.data}))
// Fetch the list on first mount
componentDidMount() {
  this.getList();
}

// Retrieves the list of items from the Express app
getList = () => {
 axios.get('/main')
 .then(res=> res.data)
 .then(list => this.setState({list}))
 .catch(error => this.setState({error: error.message}))
}

我会建议您对设计进行一些更改,因为我在许多项目中成功使用了 axios,这不是必需的,但它有帮助并且工作非常可靠:

创建类似 api.js

的服务

import axios from 'axios';

export default axios.create({
  baseURL: `http://my.api.url/`
});

那你就可以这样使用了

import API from '../Services/api'; // this is your service you created before

LoadStats = async event => {
    try {
        var response = await API.get('api/targetroute');
        if (response.data != null) {
            this.setState({
                stats: {
                    mydata: response.data
                }
            });
            console.log('Receiving result: '+JSON.stringify(response.data));
        }
    } catch (error) {
        console.log('ERROR: '+error)
    }
}