好客租房135-获取并处理城市列表数据(热门处理数据)
import React from 'react'
import axios from 'axios'
//导入axios
//导入navBar组件
import { NavBar, Icon } from 'antd-mobile'
import './index.scss'
// 数据格式化的方法
// list: [{}, {}]
const formatCityData = list => {
const cityList = {}
// const cityIndex = []
// 1 遍历list数组
list.forEach(item => {
// 2 获取每一个城市的首字母
const first = item.short.substr(0, 1)
// 3 判断 cityList 中是否有该分类
if (cityList[first]) {
// 4 如果有,直接往该分类中push数据
// cityList[first] => [{}, {}]
cityList[first].push(item)
} else {
// 5 如果没有,就先创建一个数组,然后,把当前城市信息添加到数组中
cityList[first] = [item]
}
})
// 获取索引数据
const cityIndex = Object.keys(cityList).sort()
return {
cityList,
cityIndex
}
}
class cityList extends React.Component {
state = {
cityList: [],
}
componentDidMount() {
this.getCityList()
}
async getCityList() {
const res = await axios.get('http://localhost:8080/area/city?level=1')
console.log(res, 'resss')
const { cityList, cityIndex } = formatCityData(res.data.body)
console.log(cityList, cityIndex)
const hotRes = await axios.get('http://localhost:8080/area/hot')
console.log(hotRes, 'hotRes')
cityList['hot']=hotRes.data.body
cityIndex.unshift("hot")
console.log(cityList, cityIndex,"hotList")
}
render() {
return (
<div className="citylist">
<NavBar
className="navbar"
mode="light"
icon={<i className="iconfont icon-back" />}
onLeftClick={() => this.props.histoty.push.go(-1)}
// 导航栏右边内容
// rightContent={[
// <Icon
// key="0"
// type="search"
// style={{ marginRight: '16px' }}
// />,
// <Icon key="1" type="ellipsis" />,
// ]}
>
城市选择
</NavBar>
</div>
)
}
}
export default cityList
运行结果