使用react-refetch來簡化api獲取數據的代碼
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獲取數據的邏輯用高階組件抽離出來,下面我們再用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邏輯也添加了
分離列表和項目的職責
很明顯,List組件是一個渲染列表的組件,他的職責就是渲染列表,但是我們在這里也處理了單個Item的邏輯,我們可以將其進行職責分離,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方法接收一個函數作為參數,這個函數返回一個對象,如果結果對象的值是一個字符串,那么獲取prop后,會對這個字符串發起請求,但是如果值是一個函數,那么不會立即執行,而是會傳遞給組件,以便后續使用
值為字符串
const connectWithStar = refetchConnect(() => ({gists: `https://api.github.com/users/gaearon/gists`}))
值為函數
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函數會被傳遞給Gist的prop,然后就可以在Gist里面使用了
connectWithStar(Gist)
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VeVb武林網。
新聞熱點
疑難解答