详解react-refetch的使用小例子
程序员文章站
2023-02-25 08:01:57
使用react-refetch来简化api获取数据的代码
const list = ({data: gists}) => {
return (...
使用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)
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
上一篇: 推荐一个基于Node.js的表单验证库
下一篇: 今日趣图,没心没肺的动物搞笑图片