taro 接口封装和调用 以豆瓣api为例

接口request封装

代码如下

import Taro from '@tarojs/taro'
export default function request(url, options) {
  let newOptions = { ...options };
  if (newOptions.method === 'POST' || newOptions.method === 'PUT') {
    if (!(newOptions.body instanceof FormData)) {
      newOptions.header = {
        Accept: 'application/json',
        'Content-Type': 'application/json; charset=utf-8',
        ...newOptions.header
      };
    } else {
      // newOptions.body is FormData
      newOptions.header = {
        Accept: 'application/json',
        ...newOptions.header
      };
    }
  } else {
    newOptions.header = {
      'Content-Type': 'json',  // 这里是特殊处理
      ...newOptions.header
    }
  }

  return Taro.request({url, ...newOptions})

}

复制代码
接口api的调用

代码如下

import {stringify} from 'qs';
import request from '../utils/request';
import Config from '../common/config';

export async function getInTheaters(params) {
  return request(`${Config.API_HOST}/movie/in_theaters?${stringify(params)}`);
}

复制代码
页面数据的使用

代码如下

import Taro, {Component, Config} from '@tarojs/taro'
import {View, Text, Image, Swiper, SwiperItem} from '@tarojs/components'
import {getInTheaters} from '../../service/api'
import './index.scss'

export default class Index extends Component {
  constructor(props) {
    super(props)
  }

  state = {
    list: [], // 广告列表
    start: 1,
  }
  config: Config = {
    navigationBarTitleText: '首页'
  }

  componentDidMount() {
    this.getList();
  }
  getList = async () => {
    const params: object = {
      apikey: "0b2bdeda43b5688921839c8ecb20399b",
      start: this.state.start,
      city:'上海',
      count: 15
    };
    const res = await getInTheaters(params);
    this.setState({
      list: res.data.subjects
    });
  };
  ...

}
复制代码
具体项目案例可以参看 看github代码
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值