react-refetch怎么用-创新互联

这篇文章给大家分享的是有关react-refetch怎么用的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

10年积累的成都网站设计、网站制作经验,可以快速应对客户对网站的新想法和需求。提供各种问题对应的解决方案。让选择我们的客户得到更好、更有力的网络服务。我虽然不认识你,你也不认识我。但先网站制作后付款的网站建设流程,更有铁东免费网站建设让你可以放心的选择与我们合作。

使用react-refetch来简化api获取数据的代码

const List = ({data: gists}) => {
 return (
  
       {gists.map(gist => (     {gist.description}    ))}   
 ) } 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    }  } } 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 
loading...
 } else if (gists.rejected) {   return 
{gists.reason}
 } else if (gists.fulfilled) {   return (    gists.fulfilled && 
        {gists.value.map(gist => (      {gist.description}     ))}    
  )  } } const ListWithGists = refetchConnect(() => ({gists: `https://api.github.com/users/gaearon/gists`}))(List)

瞬间清爽多了,顺便利用react-refetch提供的属性,顺便把loading逻辑也添加了

分离列表和项目的职责

很明显,List组件是一个渲染列表的组件,他的职责就是渲染列表,但是我们在这里也处理了单个Item的逻辑,我们可以将其进行职责分离,List只做列表染,而Gist也只渲染自身

const Gist = ({description}) => (
 
  •   {description}  
  • ) const List = ({gists}) => {  if (gists.pending) {   return 
    loading...
     } else if (gists.rejected) {   return 
    {gists.reason}
     } else if (gists.fulfilled) {   return (    gists.fulfilled && 
          {gists.value.map(gist => )}    
      )  } }

    使用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}) => (
     
  •   {description}   +1  
  • )

    加工Gist组件,star函数会被传递给Gist的prop,然后就可以在Gist里面使用了

    connectWithStar(Gist)

    感谢各位的阅读!关于“react-refetch怎么用”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

    另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。


    当前标题:react-refetch怎么用-创新互联
    标题路径:http://ybzwz.com/article/ecpsg.html