出處:《react設計模式和最佳實踐》
做者:米凱萊·貝爾託利
出版時間:2018年8月第1版(還算新)
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
來簡化上面的異步代碼react
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邏輯也添加了git
很明顯,List組件是一個渲染列表的組件,他的職責就是渲染列表,可是咱們在這裏也處理了單個Item的邏輯,咱們能夠將其進行職責分離,List只作列表染,而Gist也只渲染自身github
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後,會對這個字符串發起請求,可是若是值是一個函數,那麼不會當即執行,而是會傳遞給組件,以便後續使用json
值爲字符串 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)