房源列表数据-控制数据分页——获取接口数据的方法写法 & 浏览器展示接口数据
控制数据分页
- 添加分页相关参数
// 获取 Filter 组件中组装好的筛选条件数据
loadData = async (filters) => {
// 调用后台接口
const { value } = await getCurrentCity()
const res = await axios.get('/houses', {
params: {
...filters,
cityId: value,
start: 1,
end: 20
}
})
console.log('房源列表为:', res)
}
- 页面首次展示时,调用后台接口
this.state = {
currentCity: '北京',
// 房源列表数据
list: [],
// 列表长度
count: 0,
// 保存filters
filters: {}
}
componentDidMount () {
// 首次打开页面是触发接口调用
this.loadData()
}
loadData = async () => {
let cinfo = await getCurrentCity()
let res = await axios.get('/houses', {
params: {
// 筛选条件
...this.state.filters,
// 当前城市的唯一编号
id: cinfo.value,
// 分页参数
start: 1,
end: 20
}
})
this.setState({
list: res.data.body.list,
count: res.data.body.count
})
}
onFilter = async (filters) => {
// 获取筛选结果之后,调用后台接口获取房源列表数据
this.setState({
filters: filters
}, () => {
this.loadData()
})
}
实例
loadData = async (startIndex, stopIndex) => {
Toast.loading('加载中...', 0)
this.setState({
isFinished: true
})
// 封装条件查询方法(点击筛选条件的确定按钮后触发;页面首次加载也触发)
let { conditions } = this.state
conditions.cityId = this.state.city.value
// 分页参数:start表示开始查询的记录数据;end表示结束查询的记录数
conditions.start = startIndex || 1
conditions.end = stopIndex || 10
let res = await axios.get('houses', {
params: conditions
})
if (conditions.start === 1) {
this.setState({
total: res.body.count,
listData: res.body.list
})
}
this.setState({
isFinished: false
})
// if (res.body.count !== 0) {
// Toast.info(`共获取${res.body.count}条房源信息`)
// }
Toast.hide()
return res.body
}
onFilter = (conditions) => {
// 点击筛选列表的确定按钮,获取查询条件并调用接口获取数据
this.setState({
conditions: conditions
}, () => {
// 必须放到回调函数中进行
this.loadData()
})
}
调用
async componentDidMount () {
let res = await getCurrentCity()
this.setState({
city: res
}, () => {
this.loadData()
})
}
房源列表数据显示