react城市列表获取(1)

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>
        )
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值