react中使用mock.js
Posted lixingqian
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了react中使用mock.js相关的知识,希望对你有一定的参考价值。
react中使用mockjs
下载mockjs依赖
-
npm i mockjs or yran add mockjs
再项目中建立一个mock文件夹
编写api.js文件
-
import Mock from \'mockjs\'; // 模拟延迟 Mock.setup({ timeout:500 }) // 生成随机数据 Mock.mock(\'/api/v1/dataSource\',function(){ return Mock.mock({ \'code\':0, \'msg\':\'\', \'result\':{ \'list|15\':[{ \'id|+1\':1, \'userName\':\'@cname\', \'sex|0-1\':\'1\', \'status|1\':[1,2,3,4,5], \'interest|1\':[1,2,3,4,5], \'birthday\':\'2020-5-20\', \'address\':\'@province\', \'time\':\'09:00\' }], \'page\':1, \'page_size\':1, \'total\':100 } }) })
-
mockjs语法见[mockjs官网][http://mockjs.com/]
项目中引入mockjs
-
在home。js中使用
-
import axios from \'@/util/axios\'; // 引入axios import \'../mock/api\'; // 引入mock文件 // 使用数据 componentDidMount = () => { // /api/v1/dataSource 需要对应../mock/api中Mock.mock()第一个值; axios.get(\'/api/v1/dataSource\').then(res => { console.log(\'mockjs\',res); }) }
axios拦截器配置
-
import React from \'react\'; import axios from \'axios\'; import { Modal } from \'antd\'; import { createHashHistory } from \'history\'; import loading from \'../components/common/Loading\'; const history = createHashHistory(); let errorModal = false; const instance = axios.create(); instance.defaults.headers.common.Authorization = `bearer ${localStorage.getItem(\'Authorization\')}`; instance.defaults.headers.post[\'Content-Type\'] = \'application/json\'; instance.defaults.headers.put[\'Content-Type\'] = \'application/json\'; instance.defaults.timeout = 0; instance.interceptors.request.use((config) => { loading.show(); return config; }, (error) => { loading.hide(); Promise.reject(error); }); instance.interceptors.response.use((response) => { loading.hide(); const { data } = response; const isLogin = !!window.location.hash && (window.location.hash === \'#/\' || window.location.hash.startsWith(\'#/?\')); let result = null; if (data.sessionExpired) { if (!errorModal && !isLogin) { errorModal = Modal.warning({ content: data.errors[0], okText: \'确定\', onOk: () => { errorModal = null; history.push(\'/\'); }, onCancel: () => { errorModal = null; history.push(\'/\'); }, }); } result = Promise.reject(data); } else if (data.status === \'ERROR\') { if (!errorModal) { errorModal = Modal.error({ content: ( <span> {data.errors.map(err => ( <div key={Math.random()}>{err}</div> ))} </span> ), onOk: () => { errorModal = null; }, onCancel: () => { errorModal = null; }, }); } result = Promise.reject(data); } else { result = Promise.resolve(data); } return result; }, (error) => { loading.hide(); if ([\'PROD\', \'SHOW\'].includes(process.env.NODE_ENV)) { console.error(error); } else { if (!errorModal) { errorModal = Modal.error({ content: \'服务器异常,请联系系统管理员\', onOk: () => { errorModal = null; }, onCancel: () => { errorModal = null; }, }); } } return Promise.reject(error); }); export default instance;
以上是关于react中使用mock.js的主要内容,如果未能解决你的问题,请参考以下文章