詳解react-refetch的使用小例子
使用react-refetch來簡化api獲取數(shù)據(jù)的代碼
const List = ({data: gists}) => {
return (
<ul>
{gists.map(gist => (
<li key={gist.id}>{gist.description}</li>
))}
</ul>
)
}
const withData = url => Part => {
return class extends Component {
state = {data: []}
componentDidMount() {
fetch(url)
.then(response => response.json ? response.json() : response)
.then(data => this.setState({data}))
}
render() {
return <Part {...this.state} {...this.props} />
}
}
}
const ListWithGists = withData('https://api.github.com/users/gaearon/gists')(List)
上面的代碼,我們將api獲取數(shù)據(jù)的邏輯用高階組件抽離出來,下面我們再用react-refetch來簡化上面的異步代碼
import { connect as refetchConnect } from 'react-refetch'
const List = ({gists}) => {
if (gists.pending) {
return <div>loading...</div>
} else if (gists.rejected) {
return <div>{gists.reason}</div>
} else if (gists.fulfilled) {
return (
gists.fulfilled && <ul>
{gists.value.map(gist => (
<li key={gist.id}>{gist.description}</li>
))}
</ul>
)
}
}
const ListWithGists = refetchConnect(() => ({gists: `https://api.github.com/users/gaearon/gists`}))(List)
瞬間清爽多了,順便利用react-refetch提供的屬性,順便把loading邏輯也添加了
分離列表和項目的職責(zé)
很明顯,List組件是一個渲染列表的組件,他的職責(zé)就是渲染列表,但是我們在這里也處理了單個Item的邏輯,我們可以將其進行職責(zé)分離,List只做列表染,而Gist也只渲染自身
const Gist = ({description}) => (
<li>
{description}
</li>
)
const List = ({gists}) => {
if (gists.pending) {
return <div>loading...</div>
} else if (gists.rejected) {
return <div>{gists.reason}</div>
} else if (gists.fulfilled) {
return (
gists.fulfilled && <ul>
{gists.value.map(gist => <Gist key={gist.id} {...gist} />)}
</ul>
)
}
}
使用react-refetch來給Gist添加功能
react-refetch的connect方法接收一個函數(shù)作為參數(shù),這個函數(shù)返回一個對象,如果結(jié)果對象的值是一個字符串,那么獲取prop后,會對這個字符串發(fā)起請求,但是如果值是一個函數(shù),那么不會立即執(zhí)行,而是會傳遞給組件,以便后續(xù)使用
值為字符串
const connectWithStar = refetchConnect(() => ({gists: `https://api.github.com/users/gaearon/gists`}))
值為函數(shù)
const connectWithStar = refetchConnect(({id}) => ({
star: () => ({
starResponse: {
url: `https://api.github.com/gists/${id}/star?${token}`,
method: 'PUT'
}
})
}))
const Gist = ({description, star}) => (
<li>
{description}
<button onClick={star}>+1</button>
</li>
)
加工Gist組件,star函數(shù)會被傳遞給Gist的prop,然后就可以在Gist里面使用了
connectWithStar(Gist)
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
React使用react-sortable-hoc如何實現(xiàn)拖拽效果
這篇文章主要介紹了React使用react-sortable-hoc如何實現(xiàn)拖拽效果問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-07-07
Reactjs?+?Nodejs?+?Mongodb?實現(xiàn)文件上傳功能實例詳解
今天是使用?Reactjs?+?Nodejs?+?Mongodb?實現(xiàn)文件上傳功能,前端我們使用?Reactjs?+?Axios?來搭建前端上傳文件應(yīng)用,后端我們使用?Node.js?+?Express?+?Multer?+?Mongodb?來搭建后端上傳文件處理應(yīng)用,本文通過實例代碼給大家介紹的非常詳細,需要的朋友參考下吧2022-06-06
react性能優(yōu)化useMemo與useCallback使用對比詳解
這篇文章主要為大家介紹了react性能優(yōu)化useMemo與useCallback使用對比詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-08-08
react進階教程之異常處理機制error?Boundaries
在react中一旦出錯,如果每個組件去處理出錯情況則比較麻煩,下面這篇文章主要給大家介紹了關(guān)于react進階教程之異常處理機制error?Boundaries的相關(guān)資料,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下2022-08-08

