使用axios实现Ajax请求
前面将React的环境配置好了,并做了简单的练习,现在需要在文件中获取数据进行展示
1、首先,创建一个React项目,并导入到开发工具中(这里我使用的是idea)
2、在idea的终端中通过指令"npm install axios"安装axios组件,这个组件用于ajax获取请求和返回数据,安装完成后可以在node_modules目录下找到axios的包
3、为了方便数据在进行呈现时有样式,可以在项目中安装bootstrap组件
4、导入axios和bootstrap样式
import axios from “axios”
import ‘bootstrap/dist/css/bootstrap.css’
5、编写数据资源
在public下面新增数据资源目录data,在data文件夹下创建一个.json的文件,这个文件用于存放已经定义好的数据
示例:
[
{
"id": "1",
"name": "李白",
"level": "30",
"title": "刺客"
},
{
"id": "2",
"name": "安其拉",
"level": "29",
"title": "法师"
},
{
"id": "3",
"name": "盖伦",
"level": "21",
"title": "展示"
},
{
"id": "4",
"name": "后羿",
"level": "25",
"title": "射手"
}
]
6、在src文件夹中创建一个.js的文件去获取.json文件的数据并呈现在界面上,
示例:
//导入react包
import React from "react";
//导入axios组件
import axios from "axios";
//导入bootstrap组件
import 'bootstrap/dist/css/bootstrap.css';
//行组件,用于获取每一样的数据
class TrData extends React.Component {
render() {
return (
this.props.users.map((user) => {
return (
<tr key={user.id} className="text-center">
<td>{user.id}</td>
<td>{user.name}</td>
<td>{user.level}</td>
<td>{user.title}</td>
</tr>
)
})
)
}
}
//列表组件,用于获取列表展示的数据
export default class List extends React.Component {
//在构造器中定义变量
constructor(props) {
super(props);
this.state = {
//定义用户数组
users: [],
//定义是否正在加载,默认false
isLoaded: false
}
}
render() {
//如果正在加载,系统等待
if (!this.state.isLoaded) {
return <div>Loading</div>
} else {//加载完成后呈现呈现数据
return (
<table className="table table-bordered table-hover">
<thead>
<tr>
<th className="text-center">ID</th>
<th className="text-center">姓名</th>
<th className="text-center">等级</th>
<th className="text-center">称号</th>
</tr>
</thead>
{/*表格数据部分通过去调用行组件的方法获取数据进行呈现*/}
<tbody>
<TrData users={this.state.users}/>
</tbody>
</table>
)
}
}
//加载数据资源
componentDidMount() {
const _this = this;
//通过axios组件去获取路径下的文件,然后将获取到的文件内容进行赋值
axios.get('/data/user.json').then(function (response){
_this.setState({
users:response.data,
isLoaded:true
});
}).catch(function(error){//当出错时运行的代码
console.log(error);
_this.setState({
isLoaded: false,
error:error
})
})
}
}
在App.js中去调用List方法,最后呈现的结果