目录
1.安装json-server
2.创建db.json文件
3.启动JSON Server服务器
4.进行数据请求
方法一:jquery
方法二:axios
5.页面显示效果
npm install -g json-server
{
"records":[
{"id": 1, "date": "2021-01-24", "title": "收入", "amount":20},
{"id": 2, "date": "2021-05-21", "title": "收入", "amount":196},
{"id": 3, "date": "2021-06-02", "title": "收入", "amount":365},
{"id": 4, "date": "2021-06-02", "title": "支出", "amount":65},
{"id": 5, "date": "2021-11-23", "title": "收入", "amount":234},
{"id": 6, "date": "2021-12-02", "title": "收入", "amount":315},
{"id": 7, "date": "2022-01-01", "title": "支出", "amount":80},
{"id": 8, "date": "2022-01-22", "title": "收入", "amount":976},
{"id": 9, "date": "2022-02-21", "title": "收入", "amount":31},
{"id": 10, "date": "2022-03-12", "title": "支出", "amount":825},
{"id": 11, "date": "2022-03-30", "title": "支出", "amount":10}
]
}
json-server --watch db.json --port 3004
启动成功
在项目路径下安装jQuery
cnpm i jquery -S
Records.js中调用jQuery
import React,{ Component } from "react";
import Record from './Record';
import $ from 'jquery';
class Records extends Component{
constructor() {
super();
this.state = {
records: []
}
}
componentDidMount(){
$.getJSON("http://localhost:3004/records").then(
response => this.setState({records: response}),
error => console.log(error.responseText),
)
}
render(){
return (
Records
Date
Title
Amount
{this.state.records.map((record, id) => )}
);
}
}
export default Records;
被调组件Record.js文件
import React,{ Component } from "react";
class Record extends Component{
render(){
return (
{this.props.record.date}
{this.props.record.title}
{this.props.record.amount}
);
}
}
export default Record;
在项目路径下安装Axios
npm install axios -S
Records.js中调用Axios
import React,{ Component } from "react";
import Record from './Record';
import axios from 'axios';
class Records_axios extends Component{
constructor() {
super();
this.state = {
error: null,
isLoaded: false,
records: []
}
}
componentDidMount(){
axios.get("http://localhost:3004/records").then(
response => this.setState({
records: response.data,
isLoaded: true,
}),
).catch(
error => this.setState({
isLoaded: true,
error,
}),
)
}
render(){
const {error, isLoaded, records} = this.state;
if (error) {
return Error: {error.message};
}
else if (!isLoaded){
return Loading...;
}
else {
return (
Records
Date
Title
Amount
{records.map((record, id) => )}
);
}
}
}
export default Records_axios;
被调组件Record.js文件与上方一致。