react請求數(shù)據(jù)用“componentDidMount”鉤子。React的數(shù)據(jù)請求是在鉤子函數(shù)componentDidMount()中進(jìn)行的,該函數(shù)可以用來加載外部數(shù)據(jù),或處理其他的副作用代碼。
本教程操作環(huán)境:Windows7系統(tǒng)、react17.0.1版、Dell G3電腦。
React的數(shù)據(jù)請求是在鉤子函數(shù):componentDidMount 中進(jìn)行的
componentDidMount方法中的代碼,是在組件已經(jīng)完全掛載到網(wǎng)頁上才會調(diào)用被執(zhí)行,所以可以保證數(shù)據(jù)的加載。此外,在這方法中調(diào)用setState方法,會觸發(fā)重渲染。所以,官方設(shè)計這個方法就是用來加載外部數(shù)據(jù)用的,或處理其他的副作用代碼。
針對React中使用起來較為方便的幾種數(shù)據(jù)請求方式進(jìn)行了匯總,主要有以下三種,都是通過json-server模擬數(shù)據(jù)請求的接口。
1 axios
這種方法使用較為普遍,在vue中也是經(jīng)常使用
使用前先下載一哈: npm i axios
axios.get(' http://localhost:3000/datalist').then(res=>{ console.log(res); })
結(jié)果:
2 fetch方式
fetch是一種HTTP數(shù)據(jù)請求的方式,是XMLHttpRequest的一種替代方案。fetch不是ajax的進(jìn)一步封裝,而是原生js。Fetch函數(shù)就是原生js,沒有使用XMLHttpRequest對象?!疽詅etch】
fetch('http://localhost:3000/datalist').then(res=>res.json()).then(res=>{ console.log(res) })
結(jié)果:
3 傳統(tǒng)的ajax請求
這個大家應(yīng)該都不陌生就不細(xì)說了,當(dāng)然在react也是可以用它的
let xhr = new XMLHttpRequest(); xhr.addEventListener('load',handler); xhr.open("GET",'http://localhost:3000/datalist'); xhr.send(); function handler(e){ console.log(JSON.parse(e.currentTarget.response)); }
結(jié)果:
【