接口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
});
};
...
}
复制代码