本篇主要介绍读取变量,读取props,读取模拟的异步数据,读取本地文件。
一、模拟同步数据
1、写在函数的变量里面或者写在全局变量
let listData = [{id: '001', name: 'banana'},{id: '002', name: 'orange'},{id: '003', name: 'apple'}];
2、写在defaultProps里面,或者this.state里面
如果前端框架用的是react,把假数据写在defaultProps里面,然后解构读取this.props,或者把假数据写在this.state里面,然后解构读取this.state。
// render函数render() { let {data} = this.props; return (); }// defaultpropsFakeData.defaultProps = { 'data': [ { 'id': '001', 'name': 'banana' }, { 'id': '002', 'name': 'orange' }, { 'id': '003', 'name': 'apple' } ]};
{ data.map((item, i) => { return id name }) } {item.id} {item.name}
二、模拟异步数据
1、写同步数据,放进异步函数,产生异步数据。
// 写法A,promisecomponentDidMount() { let listData = [ { 'id': '001', 'name': 'banana' }, { 'id': '002', 'name': 'orange' }, { 'id': '003', 'name': 'apple' } ]; function mockAPI(url) { return new Promise((resolve, reject) => { setTimeout(() => { resolve(listData); }, 300); }); } mockAPI('/api/list').then((data) => { this.setState({ listData: data }); }); }
// 写法B,asynccomponentDidMount() { function mockAPI(result, time = 1000) { return new Promise((resolve, reject) => { setTimeout(() => { resolve(result); }, time); }); } let self = this; async function getData() { let result = []; for (let i = 1; i <= 5; i++) { result.push({ 'id': i, 'name': Math.random().toString(36).substr(2)}); } const r = await mockAPI(result); self.setState({ listData: r }); } getData(); }
// 写法C,generatorcomponentDidMount() { function * mockAPI(dataArr, time = 1000) { yield new Promise((resolve, reject) => { setTimeout(() => { resolve(dataArr); }, time); }); } let self = this; let dataArr = []; for (let i = 1; i <= 5; i++) { dataArr.push({ 'id': i, 'name': Math.random().toString(36).substr(2)}); } let g = mockAPI(dataArr); let result = g.next(); result.value.then(function(res){ console.log(res); console.log(g.next(res)); console.log(g.next(res).value); self.setState({ listData: res }); }); }
2、从文件读取数据(本地文件)
// promise, get函数另写componentDidMount() { let self = this; get(`${FILE_PATH}/list.json`).then(function(response) { console.log("Success!", JSON.parse(response)); self.setState({ listData: JSON.parse(response).data }); }, function(error) { console.error("Failed!", error); });}
// generator函数componentDidMount() { function * mockAPI(url) { yield fetch(url); } const self = this; let g = mockAPI(`${FILE_PATH}/books.json`); let result = g.next(); result.value.then(function(response) { // 这里只能得到response对象 return response.json(); }).then(function(data) { // 这里得到数据 console.log(data); console.log(g.next(data)); self.setState({ listData: data.data }); return g.next(data).value; });}
// asynccomponentDidMount() { async function mockAPI(url) { let f = await fetch(url); return f; } const self = this; let f = mockAPI(`${FILE_PATH}/books.json`); f.then(function(response) { return response.json(); }).then(function(data) { console.log(data); self.setState({ listData: data.data }); }); }
3、从文件读取数据(mock,测试)
A、安装json-server,mockjs
B、写db.js
// 在mock目录下建立db.js文件let Mock = require('mockjs');let Random = Mock.Random;module.exports = function() { var data = { news: [] }; var images = [1, 2, 3].map(x => Random.image('200x100', Random.color(), Random.word(2, 6))); for (var i = 0; i < 100; i++) { var content = Random.cparagraph(0, 10); data.news.push({ id: i, title: Random.cword(8, 20), desc: content.substr(0, 40), tag: Random.cword(2, 6), views: Random.integer(100, 5000), images: images.slice(0, Random.integer(1, 3)) }); } return data;}
C、修改package.json文件
// 在scripts加"mock": "json-server mock/db.js -p 3000"
D、启动接口,并访问。
npm run mock在浏览器打开http://localhost:3000/news