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

3,880 阅读1分钟
接口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代码