react-refetch的使用小例子

碼碼碼畜發表於2019-02-17

出處:《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來簡化上面的非同步程式碼

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)

相關文章