当前位置:  开发笔记 > 编程语言 > 正文

react怎么mock数据

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

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

本教程操作环境: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)打印数据如下图:

这样mock数据就成功了。

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

以上就是react怎么mock数据的详细内容,更多请关注其它相关文章!

推荐阅读
可爱的天使keven_464
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有