import React from 'react'
// 導入axios
import axios from 'axios'
// 1 導入 NavBar組件
import { NavBar } from 'antd-mobile'
// 導入樣式
import './index.scss'
/*
// 接口返回的數據格式:
[{ "label": "北京", "value": "", "pinyin": "beijing", "short": "bj" }]
// 渲染城市列表的數據格式爲:
{ a: [{}, {}], b: [{}, ...] }
// 渲染右側索引的數據格式:
['a', 'b']
*/
// 數據格式化的方法
// 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
}
}
export default class CityList extends React.Component {
componentDidMount() {
this.getCityList()
}
// 獲取城市列表數據的方法
async getCityList() {
const res = await axios.get('http://localhost:8080/area/city?level=1')
// console.log('城市列表數據:', res)
const { cityList, cityIndex } = formatCityData(res.data.body)
/*
1 獲取熱門城市數據
2 將數據添加到 cityList 中
3 將索引添加到 cityIndex 中
*/
const hotRes = await axios.get('http://localhost:8080/area/hot')
// console.log('熱門城市數據:', hotRes)
cityList['hot'] = hotRes.data.body
// 將索引添加到 cityIndex 中
cityIndex.unshift('hot')
console.log(cityList, cityIndex)
}
render() {
return (
<div className="citylist">
{/* 頂部導航欄 */}
<NavBar
className="navbar"
mode="light"
icon={<i className="iconfont icon-back" />}
onLeftClick={() => this.props.history.go(-1)}
>
城市選擇
</NavBar>
</div>
)
}
}