首页 > web前端 > js教程 > react怎么mock数据

react怎么mock数据

coldplay.xixi
发布: 2023-01-04 09:36:32
原创
6131 人浏览过

react mock数据的方法:首先在public目录下建立【/api/headerList.json】文件;然后加入相关代码【axios.get('/api/headerList.json')】。

react怎么mock数据

本教程操作环境:windows7系统、React17版、thinkpad t480电脑。

react mock数据的方法:

如下代码,在input获得焦点时调用getList()方法。

const mapDispathToProps = (dispatch) => {
    return {
        handleInputFocus() {
            dispatch(actionCreators.getList())
        }
    }
}
登录后复制

getList()方法是通过Ajax获取数据,此时后端并没有写好,所以自己mock一个数据。

export const getList = () => {
    return (dispatch) => {
        axios.get('/api/headerList.json').then((res) => {
            const data = res.data;
            console.log(data)
        }).catch(() => {
            console.log('error')
        })
    }
}
登录后复制

axios.get('/api/headerList.json')这句代码,计算机会首先去src目录下寻找/api/headerList.json,没有找到然后去public目录下找,此时我们在public目录下建立/api/headerList.json文件,文件如下:

{
    "success":true,
    "data":["微信","支付宝","蚂蚁金服","被骗","借呗","诈骗","盗窃","pandas","TensorFlow","PyTorch","Caffe","scikit-learn","Python","Keras","pyecharts","ggplot","Matplotlib","Gensim","Bokeh","Theano","Scrapy","SciPy","Plotly","NumPy","XGBoost","是","他","有","光大永明","我","要","人","Android","女","大","不","着","男","它","二","于","中","java","把","上","这","下","的","了","来"]
}
登录后复制

此时返回的数据就是以上数据,通过console.log(res.data)打印数据如下图:

4751c021da62248b892f3a1920ec4ce.png

这样mock数据就成功了。

相关免费学习推荐:javascript(视频)

以上是react怎么mock数据的详细内容。更多信息请关注PHP中文网其他相关文章!

相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
最新问题
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板