1.npm add mockjs --dev 安装mock环境
2.src 目录下新建mock文件夹,文件夹中新建mock.js
3.mock.js数据生成如下:
import Mock from ‘mockjs’
export default Mock.mock(‘http://localhost:8000/getdata’,‘get’,//拦截/getdata的GET请求
{
“userInfo|4”:[{
“id|+1”:’@id’,
‘title’:’@ctitle’,
‘author’:’@cauthor’,
‘date’:’@date’,
‘img’:Mock.Random.image(‘200x100’)
}]
}
);
4.在需要使用数据的组件中访问mock
import React,{Component} from ‘react’;
import PostItem from ‘./Postltem’;
import mock from “…/mock/mock”;
import axios from “axios”
class PostList extends Component{
constructor(props){
super(props);
this.state = {
news:[
{
title:“大家一起来讨论React吧”,
author:“张三”,
date:“2017-09-01 10:00”,
img:""
}
]
};
}
handle_click = ()=>{
let t = this;
fetch(“data”, {method: ‘GET’}).then(
function (res) {
console.log(res);
res.json().then(function (data) {
console.log(data);
t.setState({
news:data
});
}
)
});
console.log("news",this.state.news)
};
onbtnclick = ()=>{
let t = this;
axios.get('http://localhost:8000/getdata')
.then(function(res){
alert(JSON.stringify(res.data))
t.setState({
news:res.data.userInfo
});
}).catch(
function(res)
{
alert(res);
}
)
console.log("news",this.state.news)
};
render() {
return (
<div>
<button onClick={this.onbtnclick}>button</button>
<br/>
帖子列表:
{this.state.news.map((item,i) =>
<div key={i}>
<PostItem
title = {item.title}
author = {item.author}
date = {item.date}
img = {item.img}
/>
</div>
)}
</div>
);
}
}
export default PostList;