React项目--如何mock数据?
## 前言
在开发项目时,前端需要和后端对接数据,但有时后端并没有写好数据,前端还需要继续往下开发,这时候就需要mock数据了。
如何mock数据?
如下代码,在input获得焦点时调用getList()方法。1
2
3
4
5
6
7const mapDispathToProps = (dispatch) => {
return {
handleInputFocus() {
dispatch(actionCreators.getList())
}
}
}
getList()方法是通过Ajax获取数据,此时后端并没有写好,所以自己mock一个数据。1
2
3
4
5
6
7
8
9
10export 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文件,文件如下:
1 | { |
此时返回的数据就是以上数据,通过console.log(res.data)打印数据如下图:
这样mock数据就成功了。