环境搭建
安装官方脚手架
npm install create-react-app -g
运行脚手架工具
create-react-app react-demo
生成的项目结构如下:
启动项目
npm start
mockjs
npm install mockjs --save
新建js文件
import Mock from 'mockjs';
Mock.mock('http://api/comments', [
{
"author":"@name",
"body":"@name"
},
{
"author":"小明",
"body":"@name评论2"
},
{
"author":"小明",
"body":"@name评论1"
},
{
"author":"小明",
"body":"@name|评论1"
}
]);
ajax加载数据
//引入上面的js文件
import data from './mock';
//dom加载完成后要做的事情
componentDidMount(){
this.getData();
}
//获取数据
getData(){
$.ajax({
url:"http://api/comments",
type:'get',
dataType:"json",
//箭头函数 自动绑定this
success: (comments) => {
// console.log(comments);
this.setState({
comments:comments
});
},
error: (xhr,status,err) =>{
console.log("err.toString")
}
})
}