1页面加载时 根据接口获取列表数据
2分析当前数据格式以及改功能需要的数据格式
3渲染数据
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) } render() { return ( <div className="citylist"> <NavBar className="navbar" mode="light" icon={<i className="iconfont icon-back" />} onLeftClick={() => this.props.histoty.push.go(-1)} // 导航栏右边内容 // rightContent={[ // // key="0" // type="search" // style={{ marginRight: '16px' }} // />, // , // ]} > 城市选择 </NavBar> </div> ) } } export default cityList
运行结果