目录
1.安装json-server
npm install -g json-server
2.创建db.json文件,文件内容示例(最后一行数据没有逗号,否则会导致步骤3启动失败):
{
"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}
]
}
3.db.json文件路径下,启动JSON Server服务器,端口号默认为3000,需要修改为别的端口号(例如3004)
json-server --watch db.json --port 3004
启动成功
4.进行数据请求
方法一:使用jquery调用json-server
在项目路径下安装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 (
<div>
<h2>Records</h2>
<table className="table table-bordered">
<thead>
<tr>
<th>Date</th>
<th>Title</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
{this.state.records.map((record, id) => <Record key={record.id} record={record} />)}
</tbody>
</table>
</div>
);
}
}
export default Records;
被调组件Record.js文件
import React,{ Component } from "react";
class Record extends Component{
render(){
return (
<tr>
<td>{this.props.record.date}</td>
<td>{this.props.record.title}</td>
<td>{this.props.record.amount}</td>
</tr>
);
}
}
export default Record;
方法二:使用axios调用json-server
在项目路径下安装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 <div>Error: {error.message}</div>;
}
else if (!isLoaded){
return <div>Loading...</div>;
}
else {
return (
<div>
<h2>Records</h2>
<table className="table table-bordered">
<thead>
<tr>
<th>Date</th>
<th>Title</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
{records.map((record, id) => <Record key={record.id} record={record} />)}
</tbody>
</table>
</div>
);
}
}
}
export default Records_axios;
被调组件Record.js文件与上方一致。