2021-10-10

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;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值