react前端调试时使用json-server本地模拟后端数据

目录

1.安装json-server

2.创建db.json文件

3.启动JSON Server服务器

4.进行数据请求

方法一:jquery

方法二:axios

5.页面显示效果


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

启动成功 

react前端调试时使用json-server本地模拟后端数据_第1张图片

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 (
		

Records

{this.state.records.map((record, id) => )}
Date Title Amount
); } } 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调用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 
Error: {error.message}
; } else if (!isLoaded){ return
Loading...
; } else { return (

Records

{records.map((record, id) => )}
Date Title Amount
); } } } export default Records_axios;

被调组件Record.js文件与上方一致。

5.页面显示效果

react前端调试时使用json-server本地模拟后端数据_第2张图片

你可能感兴趣的:(前端)