react 使用mock.js模拟后台数据

1、cnpm install mockjs -S

2、在index.js引入mock.js文件
	判断是否是生产环境
	if(process.env.NODE_ENV=='development')
		{
		  require("mock.js文件所在路径");
		}
		
3、创建js文件
	(1)引入
		var Mock = require('mockjs')
	
	(2)设置数据返回时间
		Mock.setup({
		    timeout:毫秒,
		})
	
	(3)设置返回数据:
	
		Mock.mock('请求的url地址',{
		     xx:'返回的数据'
		    "xx":"@datetime",  返回随机时间戳
		    "xx|1-800":800,   返回1-800的随机数
		    "xx":"@cname",   返回随机名字 
		    'xx|1-10': [{   返回1-10个随机元素的数组
		        'xx|+1': 10,   返回从10开始,每次自增1的数据
		    }],
		    "xx":"@url",  返回随机url地址
		    "xx":"@image",   返回随机图片
		    "xxl":"@email",  返回随机email
		    "xx":Mock.Random.cword(5,20)  返回5-20个随机汉字
		
		})

代码示例:
index.js:

import React from 'react';
import ReactDOM from 'react-dom';
import {Provider} from 'react-redux'
import App from './App';
import * as serviceWorker from './serviceWorker';
import store from './store/store'

if(process.env.NODE_ENV=='development')
{
  require("./mock/mock");
}


ReactDOM.render(
  <Provider store={store}>
    <React.Fragment>
       <App  />
    </React.Fragment>
  </Provider>
  ,
  document.getElementById('root')
);

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();

mock.js:

var Mock = require('mockjs')

Mock.setup({
    timeout:1000,

})

Mock.mock('/api/banner',{
    username:'jeff',
    userpwd:'123',
    sex:'男',
    special:'帅',
    "date":"@datetime",
    "score|1-800":800,
    "rank|1-100":100,
    "name":"@cname",
    'list|1-10': [{
        'id|+1': 10,
        'num|20-30':30
    }],
    "address":"@url",
    "img":"@image",
    "email":"@email",
    "text":Mock.Random.cword(5,20)

})

你可能感兴趣的:(React,react)