react中如何mock数据
创始人
2024-11-18 18:34:02
0次

1.需求说明

因为前后端分离开发项目,就会存在前端静态页面写好了,后端数据接口还没写好;这时候前端就需要自己定义数据来使用。

定义数据有三种方式:直接写死数据、使用mock软件、json-server工具

这里讲解通过json-server工具来获取数据

2.安装插件

npm i -D json-server

3.新建数据文件

在根目录下新建server文件,该文件夹下新建data.json文件用于存储数据

4.更改项目配置文件

package.json

更改前

"scripts": {     "start": "react-scripts start",     "build": "react-scripts build",     "test": "react-scripts test",     "eject": "react-scripts eject"   },

更改后

"scripts": {     "start": "react-scripts start & npm run server",     "build": "react-scripts build",     "test": "react-scripts test",     "eject": "react-scripts eject",     "server": "json-server ./server/data.json --port 8888"   },

说明:

1.需要同时启动项目和工具,工具启动命令是npm run server,项目启动命令是npm run start

2."server": "json-server ./server/data.json --port 8888"代码意思是,server是启动命令、json-server是工具、./server/data.json是数据源位置、--port 8888是设置端口号

3."start": "react-scripts start & npm run server"的意思是,start是启动命令、react-scripts start不知道是什么、& npm run server是代表同时启动server工具;整行代码就是通过npm run start就同时启动项目和启动server工具

4.启动项目和工具可以分开在两个终端控制台启动,分别在两个终端控制台输入各自的命令就行了;也可以在一个控制终端上通过npm run start,前提是有写"react-scripts start & npm run server"

5.测试

import axios from "axios" function Home() {     async function shower() {         // await axios.get('http://localhost:8888/kanno').then(res=>{             // console.log('res:', res.data);          // }) // 通过axios来请求数据         const response = await fetch('http://localhost:8888/kanno'); // 通过fetch来请求数据         const data = await response.json();         console.log('Data:', data);     }     return (         
我是home
) } export default Home

说明:接口地址来源于使用npm run server启动server工具时

6.最终效果

上一篇:House Of Force

下一篇:React的生命周期?

相关内容

热门资讯

每日必看教程!微乐小程序黑科技... 每日必看教程!微乐小程序黑科技免费(辅助器),微信小程序怎么开挂(有辅助挂教学)1、让任何用户在无需...
今日公布!微乐小程序免费黑科技... 今日公布!微乐小程序免费黑科技(透视器),微信小程序微乐辅助器教程图片(有辅助挂辅教程)1、完成微乐...
安装程序教程!微乐小程序辅助工... 安装程序教程!微乐小程序辅助工具(透视器),微乐小程序黑科技辅助工具2026最新推荐(证实有辅助挂)...
我来教大家!微乐小程序黑科技免... 我来教大家!微乐小程序黑科技免费(辅助),微信小程序微乐安徽辅助苹果(确实有辅助挂)1)微乐小程序黑...
热点推荐!微乐小程序黑科技免费... 热点推荐!微乐小程序黑科技免费(辅助),微信小程序透视微乐(竟然有辅助挂)1、微乐小程序黑科技免费破...
揭秘几款!微乐小程序免费黑科技... 揭秘几款!微乐小程序免费黑科技(辅助),微信微乐陕西小程序破解器(有辅助挂辅助)揭秘几款!微乐小程序...
重大通报!微乐小程序免费黑科技... 重大通报!微乐小程序免费黑科技(辅助),微乐游戏辅助脚本安装(有辅助挂辅助)1、每一步都需要思考,不...
玩家交流!微乐小程序免费黑科技... 玩家交流!微乐小程序免费黑科技(作弊器),微乐家乡官方app下载(有辅助挂辅教程)1)微乐小程序免费...
教程攻略!微乐小程序黑科技免费... 教程攻略!微乐小程序黑科技免费(开挂),微乐小程序游戏破解器下载(有辅助挂方式)1、不需要AI权限,...
终于清楚!微乐小程序黑科技免费... 终于清楚!微乐小程序黑科技免费(作弊器),微乐小程序辅助教程(有辅助挂秘籍)1、用户打开应用后不用登...