import React from 'react'
//导入的ant-moblie ui组件
import { NavBar, Icon } from 'antd-mobile';
import './index.scss'
import axios from 'axios'
//工具包utils的获取当前定位城市
import {getCurrentCity} from '../../utils'
// 数据格式化方法:把获取的城市列表按照ui图需要划分成以首字符排列的数据
const formatDataCity = (list)=>{
//存储以首字符开头的城市数据{}
const cityList = {}
// const cityIndex = []
// 1.遍历list数组
list.forEach(item=>{
// 2.获取每个城市首字母
const first= item.short.substr(0,1)
console.log(first)
// 3.判断cityList是否有该分类
if(cityList[first]){
// 4.如果有就往该分类中push数据
cityList[first].push(item)
} else{
// 5.如果没有就创建新数组存储
cityList[first] = [item]
}
})
// 获取索引数据
const cityIndex=Object.keys(cityList).sort()
return{
cityList,
cityIndex
}
}
export default class CityList extends React.Component{
// 获取城市列表数据
async getCityLists(){
const res = await axios.get('http://localhost:8080/area/city?level=1')
console.log(res)
const{cityList,cityIndex}= formatDataCity(res.data.body)
const hot = await axios.get('http://localhost:8080/area/hot')
cityList['hot'] = hot.data.body
// 将索引添加到cityIndex中
cityIndex.unshift('hot')
// 获取当前定位城市
const curCity = await getCurrentCity()
// 把当前定位城市加到cityList中
cityList['#'] = [curCity]
cityIndex.unshift('#')
console.log(cityList,cityIndex,curCity)
}
componentDidMount(){
this.getCityLists()
}
render(){
return (
<div className="cityList">
<NavBar
mode="light"
icon={<i className="iconfont icon-back"/>}
onLeftClick={() => this.props.history.go(-1)}
>城市列表</NavBar>
</div>
)
}
}
react城市列表获取(1)
最新推荐文章于 2023-02-25 16:00:32 发布