Serverless-实现bing每日壁纸API(三)

311 阅读2分钟

前面做完了bing壁纸的云函数,包括定时抓取最新壁纸的函数和提供api的函数:

Serverless-实现bing每日壁纸API(一)

Serverless-实现bing每日壁纸API(二)

这篇就利用这个api实现一个简单的小程序

Taro

纯粹是想试试这个,所以选择了 taro-docs.jd.com/taro/ 做为小程序的实现方案。Taro几乎可以提供全平台的小程序开发支持,一套代码可以输出微信小程序,支付宝小程序,百度小程序等等等...

安装和使用的教程可以直接参考官网

直接贴代码

import Taro, { Component } from '@tarojs/taro'
import { View, Text } from '@tarojs/components'
import './index.scss'

export default class Index extends Component {


  componentDidMount() {
    Taro.startPullDownRefresh()
  }

  config = {
    navigationBarTitleText: '首页',
    enablePullDownRefresh: true
  }
  constructor(props) {
    super(props)
    this.state = {
      list: [],
      offset: 0,
      limit: 10
    }
  }


  onPullDownRefresh() {
    console.log("pull down")
    this.fetchBingPaperList(0, this.state.limit)
  }

  onReachBottom() {
    this.fetchBingPaperList(this.state.offset, this.state.limit)
  }

  fetchBingPaperList(offset, limit) {
    let scope = this
    //调用云函数获取bing壁纸列表
    Taro.request({
      url: 'https://service-jmhm1hno-1256668370.gz.apigw.tencentcs.com/release/bing_wallpaper_api',
      data: {
        offset: offset,
        limit: limit
      },
      success(res) {
        console.log(res)
        let { code, data } = res.data
        console.log(code, data)
        if (code != 200) {
          Taro.showToast(`服务异常:${code}`)
        }
        //更新state
        if (offset == 0) {
          scope.setState({
            list: data,
            offset: data.length
          })
        } else {
          scope.setState({
            list: scope.state.list.concat(data),
            offset: scope.state.offset + data.length
          })
        }
        Taro.stopPullDownRefresh()
      }
    })
  }

  render() {
    const parentStyle = {
      height: '100vx'
    }
    const labelStyle = {
      fontSize: '10px',
      left: '10px',
      bottom: '30px',
      background: 'white',
      textOverflow: 'ellipsis',
      whiteSpace: 'nowrap',
      width: '200px'
    }

    return (
      <View
        style={parentStyle}
      >
        {
          //显示壁纸
          this.state.list.map((item) => {
            let imgUrl = `https://bing-1256668370.file.myqcloud.com/${item.fullstartdate}.png/thumb`
            let style = {
              width: '100%',
              height: '200px',
              background: `url(${imgUrl}) no-repeat center center`,
              marginBottom: '4px'
            }
            return <View key={item.id} style={style}>
              <Text style={labelStyle}>{item.copyright}</Text>
            </View>
          })
        }

      </View>
    )
  }
}

非常简单的一个列表展示,下拉刷新,上拉加载更多。效果如下:

完结

至此,一个完整的利用serverless云函数的方式开发的简单应用就完成了,可以看到在这个案例中,相比较传统的搭建服务器的方式,serverless的方式确实会更加简单方便,尤其对于前端开发来说,可以自己实现完整的产品逻辑,不需要去寻求后端开发的帮助。

当然,微信小程序里面自己有完成的云函数和存储的实现,如果只是做微信小程序的实现的话,完全可以直接用微信小程序自己的开发框架,会更加的方便:

developers.weixin.qq.com/miniprogram…

接下来会再考虑用云函数来实现另外一个常见的功能:生成短网址链接