taro 介面封裝和呼叫 以豆瓣api為例

呆呆_呆呆發表於2018-11-26
介面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程式碼

相關文章