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數據的詳細內容。更多資訊請關注PHP中文網其他相關文章!