React+Electron桌面應(yīng)用開發(fā)文章索引
這一篇介紹React網(wǎng)站開發(fā)過程中如何發(fā)起http請求,從服務(wù)端獲取數(shù)據(jù)佑女。
準(zhǔn)備工作
安裝superagent模塊,這是一個可以從服務(wù)器獲取get數(shù)據(jù)或者把數(shù)據(jù)推送post到服務(wù)器的工具:
zhyuzh$ cnpm i superagent --save-dev
在dist目錄下創(chuàng)建一個datas/mydata.js用于放置文件胁孙,代替服務(wù)器接口返回的數(shù)json數(shù)據(jù)笔横,所以最好使用嚴(yán)格的json格式约计,字段名都帶雙引號裳涛,最后一個字段后面不帶逗號:
[{
"title": "標(biāo)題1",
"text": "文字內(nèi)容1"
},{
"title": "標(biāo)題2",
"text": "文字內(nèi)容2"
}]
發(fā)起get請求
當(dāng)元素被添加到頁面時候木张,發(fā)起請求,注意這里使用JSON對數(shù)據(jù)進(jìn)行了轉(zhuǎn)換.
獲取數(shù)據(jù)之后,使用setState能夠讓數(shù)據(jù)立即生效端三。
HomePage.js中修改的部分:
componentDidMount() {
let that = this
superagent.get('datas/mydata.js')
.end((err, res) => {
that.setState({
mylist: JSON.parse(res.text)
})
})
}
在render()方法中舷礼,如果使用了mylist數(shù)據(jù)生成元素(比如用一個list生成多個重復(fù)界面元素),setState會在數(shù)據(jù)讀取完成后自動刷新這些元素郊闯。
類似下面的代碼:
let rightItems = []
for (let i = 0; i < this.state.articleList.length; i++) {
let data = this.state.articleList[i]
rightItems.push(h(Grid, {
item: true,
xs: 12,
sm: 6,
md: 4,
lg: 3,
}, [
h(Card, {
className: css.card
}, h(CardContent, {}, [
h(CardMedia, {
image: data.image,
className: css.cardMedia
}),
h(CardContent, {
style: {
padding: 0
},
}, data.title)
]))
]))
}
致力于讓一切變得簡單
如果您發(fā)現(xiàn)文章錯誤妻献,請不吝留言指正;
如果您覺得有用团赁,請點(diǎn)喜歡育拨;
如果您覺得很有用,歡迎轉(zhuǎn)載~
END