【发布时间】:2021-03-21 01:32:30
【问题描述】:
我尝试在 react 中从随机用户 API 创建应用程序,并使用 axios 库进行 HTTP 请求。我使用 axios.create 为基本 API 创建了一个单独的文件,文件代码如下,
import axios from 'axios'
export default axios.create({
baseURL: `http://jsonplaceholder.typicode.com`,
});
然后我在另一个文件中使用它来发出 GET 请求并将数据存储在 componentdidMount 上的state 中,以便生病可以访问 UI 中的数据。
import React from "react";
import API from "../api";
export default class PersonList extends React.Component {
state = {
persons: []
};
componentDidMount() {
API
.get('/').then((data) => {
const persons = data.data;
this.setState({ persons });
console.log(this.state.persons);
});
}
render() {
const { persons } = this.state;
console.log('Stato',persons)
return (
<ul>
{persons.map((person) => (
<li key={person.id}>{person.name}</li>
))}
</ul>
);
}
}
但它不起作用,因为状态没有填充用户数据,所以 .map() 函数抛出错误。
【问题讨论】:
标签: reactjs get axios httprequest