React八案例上

嚴華  论坛元老 | 2025-4-14 04:13:13 | 显示全部楼层 | 阅读模式
打印 上一主题 下一主题

主题 1794|帖子 1794|积分 5382

代码下载

技术栈:


  • React 核心库:react、react-dom、react-router-dom
  • 脚手架:create-react-app
  • 数据哀求:axios
  • UI组件库: antd-mobile
  • 其他组件库: react-virtualized、formik+yup、react-spring 等
  • 百度舆图API
项目搭建

摆设本地接口

后台项目这里不做详细记录,只为辅助前端开发,这是后台项目下载地址。

  • 将后台项目下载到本地,使用MySQLWorkbench新建名为 hkzf 的数据库,字符集选择 utf8,其他默认。
  • 在MySQLWorkbench中,点击 File -> Open SQL Script…,然后选中db文件夹中的 hkzf_db.sql 文件打开,双击选中mydb数据库并点击 open,点击文档编辑区域上方闪电图标执行。
  • 使用VSCode打开项目,执行 npm i 安装依靠库,进入 config/mysql.js 文件修改 module.exports 中的 password 为自己的数据库暗码。
  • 执行 npm start 运行后台项目,此时可以使用 Postman 测试相应接口,也可以在浏览器中直接打开接口文档地址 http://localhost:8080。
初始化项目

1、初始化项目:npx create-react-app react_hkzf_mobile
2、启动项目,在项目根目次执行下令 npm start,主要结构说明:
结构说明public公共资源public/index.html首页(必须有)public/manifest.jsonPWA应用的元数据src项目源码,写项目功能代码src/index.js项目入口文件(必须有)src/App.js项目的根组件src/setupTests.jsApp组件的测试文件src/reportWebVitals.js用来实现PWA(可选) 3、项目中 src 目次增加结构如下:
结构说明assets/资源(图片、字体图标等)components/公共组件pages/页面utils/工具 antd-mobile 组件库 先容

antd-mobile 中文文档
安装:
  1.     npm i antd-mobile
复制代码
导入要使用的组件,渲染组件:
  1.     import { Button } from 'antd-mobile';
  2.     function App() {
  3.       return (
  4.         <div className="App">
  5.           <Button>按钮</Button>
  6.         </div>
  7.       );
  8.     }
复制代码
配置基础路由

1、安装,在项目根目次执行 npm i react-router-dom 或 yarn add react-router-dom
2、在 src/index.html 中导入路由组件:
  1.     import { BrowserRouter as Router, Routes, Route, Link, Navigate } from "react-router-dom";
复制代码
3、在 pages 文件夹中创建 Home.js、House.js、News.js、Profile.js 和 CityList.js 五个组件
项目整体结构有两种:


  • 有TabBar的页面: 首页、找房、资讯、我的
  • 无TabBar的页面:城市选择等

TabBar 的菜单也可以实现路由切换,也就是路由内部切换路由(嵌套路由)。用 App 组件体现父路由的内容,用 Home、House、News 和 Profile 组件体现子路由的内容。
4、在 App 组件中,添加一个Route作为子路由的出口:
  1.     function App() {
  2.       return (<>
  3.         App
  4.         <Outlet></Outlet>
  5.       </>)
  6.     }
复制代码
5、在入口文件 index.js 中设置路由,子路由以父路由path开头(父组件展示了,子组件才会展示),修改 pathname 为 /home,Home 组件的内容就会展示在 APP 组件中了:
  1.         <Router>
  2.           <Routes>
  3.             {/* 父路由 */}
  4.             <Route path='/' element={<App></App>}>
  5.               {/* 子路由 */}
  6.               <Route path='/home' element={<Home></Home>}></Route>
  7.               <Route path='/house' element={<House></House>}></Route>
  8.               <Route path='/news' element={<News></News>}></Route>
  9.               <Route path='/profile' element={<Profile></Profile>}></Route>
  10.             </Route>
  11.             
  12.             <Route path='/cityList' element={<CityList></CityList>}></Route>
  13.           </Routes>
  14.         </Router>
复制代码
外貌和样式调解

1、修改页面标题,在index.html内里修改:
  1.         <title>React 好客租房案例</title>
复制代码
2、基础样式调解,在 index.css 中调解 css 样式结构:
  1.     html, body {
  2.       height: 100%;
  3.       font-family: 'Microsoft YaHei';
  4.       color: #333;
  5.       background-color: #fff;
  6.       margin: 0;
  7.       padding: 0;
  8.     }
  9.     * {
  10.       box-sizing: border-box;
  11.     }
复制代码
实现TabBar

打开 antd-mobile 组件库中TabBar的组件文档,选中共同路由使用拷贝核心代码到 App 组件中(App是父路由组件)并调解代码:
  1.     function App() {
  2.       const tabs = [
  3.         {
  4.           key: '/home',
  5.           title: '首页',
  6.           icon: 'icon-ind',
  7.         },
  8.         {
  9.           key: '/house',
  10.           title: '找房',
  11.           icon: 'icon-findHouse',
  12.         },
  13.         {
  14.           key: '/news',
  15.           title: '资讯',
  16.           icon: 'icon-infom',
  17.         },
  18.         {
  19.           key: '/profile',
  20.           title: '我的',
  21.           icon: 'icon-my',
  22.         },
  23.       ]
  24.       const location = useLocation()
  25.       const navigate = useNavigate()
  26.       console.log('-----', location.pathname);
  27.       
  28.       return (<>
  29.         <Outlet></Outlet>
  30.         <TabBar activeKey={location.pathname} defaultActiveKey='home' safeArea onChange={(key) => navigate(key)}>
  31.           {tabs.map(item => (
  32.             <TabBar.Item
  33.               key={item.key}
  34.               icon={(active) => active ? <i className={`active iconfont ${item.icon}`} /> : <i className={`iconfont ${item.icon}`} />}
  35.               title={(active) => active ? <span className={`active`}>{item.title}</span> : <span>{item.title}</span>}
  36.             />
  37.           ))}
  38.         </TabBar>
  39.       </>)
  40.     }
复制代码
修改 TabBar 组件 css 样式结构:
  1.     .active {
  2.       color: #21b97a;
  3.     }
  4.     .iconfont {
  5.       font-size: 20px;
  6.     }
  7.     .adm-tab-bar {
  8.       position: fixed;
  9.       bottom: 0;
  10.       width: 100%;
  11.     }
复制代码
设置路由重定向:
  1.         <Router>
  2.           <Routes>
  3.             {/* 路由重定向 */}
  4.             <Route path='/' element={<Navigate to='/home' replace></Navigate>}></Route>
  5.             {/* 父路由 */}
  6.             <Route path='/' element={<App></App>}>
  7.               {/* 子路由 */}
  8.               <Route path='/home' element={<Home></Home>}></Route>
  9.               <Route path='/house' element={<House></House>}></Route>
  10.               <Route path='/news' element={<News></News>}></Route>
  11.               <Route path='/profile' element={<Profile></Profile>}></Route>
  12.             </Route>
  13.             
  14.             <Route path='/cityList' element={<CityList></CityList>}></Route>
  15.           </Routes>
  16.         </Router>
复制代码
首页模块

轮播图

打开 antd-mobile 组件库的 Swiper 走马灯 组件文档,选择循环拷贝核心代码到 Home 组件中。并优化相应的结构,删除不须要的代码:
  1.     mport {Swiper, Toast } from 'antd-mobile'
  2.     import './Home.css'
  3.     const colors = ['#ace0ff', '#bcffbd', '#e4fabd', '#ffcfac']
  4.     const items = colors.map((color, index) => (
  5.       <Swiper.Item key={index}>
  6.         <div
  7.           className='content'
  8.           onClick={() => {
  9.             Toast.show(`你点击了卡片 ${index + 1}`)
  10.           }}
  11.         >
  12.           {index + 1}
  13.         </div>
  14.       </Swiper.Item>
  15.     ))
  16.     export default function Home() {
  17.         return (<>
  18.             <Swiper
  19.               loop
  20.               autoplay
  21.               onIndexChange={i => {
  22.                 console.log(i, 'onIndexChange1')
  23.               }}
  24.             >
  25.               {items}
  26.             </Swiper>
  27.         </>)
  28.     }
复制代码
修改轮播图干系 css 样式结构:
  1.     /* 轮播图 */
  2.     .content {
  3.         height: 212px;
  4.         color: #ffffff;
  5.         display: flex;
  6.         justify-content: center;
  7.         align-items: center;
  8.         font-size: 48px;
  9.         user-select: none;
  10.         img {
  11.             height: 212px;
  12.         }
  13.     }
  14.     .adm-page-indicator {
  15.         --active-dot-size: 3px;
  16.     }
复制代码
获取轮播图的数据

1、安装 axios: npm i axios
2、新建 utils > useData.js 文件,在这里配置 axios,并自定义获取网络数据的 Hook:
  1.     import { useState, useEffect } from "react";
  2.     import axios from "axios";
  3.     // 全局配置
  4.     axios.defaults.timeout = 10000 // 超时时间
  5.     axios.defaults.baseURL = 'http://127.0.0.1:8080' // 域名
  6.     // 响应拦截器
  7.     axios.interceptors.response.use((res) => {
  8.         console.log('data: ', res);
  9.         return res.data
  10.     }, (error) => {
  11.         console.log('error: ', error);
  12.     })
  13.     function useNetwork(url, stringParams, type) {   
  14.         const [data, setData] = useState(null)
  15.         const [error, setError] = useState(null)
  16.         const [loading, setLoading] = useState(true)
  17.         useEffect(() => {
  18.             console.log('stringParams:', stringParams);
  19.             let ignore = false
  20.             const request = async () => {
  21.                 try {
  22.                     let result = null
  23.                     switch (type) {
  24.                         case 'GET':
  25.                             result = await axios.get(url, stringParams && JSON.parse(stringParams))
  26.                             break;
  27.                         case 'POST':
  28.                             result = await axios.post(url, stringParams && JSON.parse(stringParams))
  29.                             break
  30.                         default:
  31.                             break;
  32.                     }
  33.                     if (!ignore && result) {
  34.                         setData(result)
  35.                     }
  36.                     setLoading(false)
  37.                 } catch (error) {
  38.                     if (!ignore) {
  39.                         setError(error)
  40.                         setLoading(false)
  41.                     }
  42.                 }
  43.             }
  44.             request()
  45.             return () => {
  46.                 ignore = true
  47.                 setLoading(false)
  48.             }
  49.         }, [url, stringParams, type])
  50.         return { data, error, loading }
  51.     }
  52.     function useGet(url, params) {
  53.         return useNetwork(url, JSON.stringify(params), 'GET')
  54.     }
  55.     function usePost(url, params) {
  56.         return useNetwork(url, JSON.stringify(params), 'POST')
  57.     }
  58.     const useData = { get: useGet, post: usePost }
  59.     export default useData
复制代码
  说明:React Effect 使用 Object.is 比力依靠项的值,如果依靠项为 对象,则比力的是是否在内存中为同一对象。自定义 Hook useNetwork 中的哀求参数需要比力的是参数内容(值)是否相同,以是将参数转化为字符串作为Effect依靠性。
  3、在 Home 组件中,导入 useData 获取数据并优化调解代码结构:
  1.     import useData from '../utils/useData'
  2.     // 渲染轮播图
  3.     function renderSwiper(data, indexChange, indexClick) {
  4.         return data && <Swiper
  5.         loop
  6.         autoplay
  7.         onIndexChange={ indexChange }
  8.         >
  9.             {data.body.map((item, index) => (
  10.                 <Swiper.Item key={index}>
  11.                     <div
  12.                     className='content'
  13.                     style={{ background: 'red' }}
  14.                     onClick={ (e) => indexClick(index, e) }
  15.                     >
  16.                         <img src={'http://127.0.0.1:8080' + item.imgSrc} style={{width: '100%'}} alt=''></img>
  17.                     </div>
  18.                 </Swiper.Item>
  19.             ))}
  20.         </Swiper>
  21.     }
  22.     export default function Home() {
  23.         const { data: swiperData } = useData.get('/home/swiper')
  24.         console.log('swiperData: ', swiperData);
  25.         
  26.         return (<>
  27.             {/* 轮播图 */}
  28.             { renderSwiper(swiperData, i => console.log('indexChange: ', i), i => Toast.show(`你点击了卡片 ${i + 1}`)) }
  29.         </>)
  30.     }
复制代码
导航菜单

1、导入图片:
  1.     // 导入所需图片
  2.     import nav1 from "../assets/images/nav-1.png";
  3.     import nav2 from "../assets/images/nav-2.png";
  4.     import nav3 from "../assets/images/nav-3.png";
  5.     import nav4 from "../assets/images/nav-4.png";
复制代码
2、构建导航菜单数据:
  1.     // 构建导航菜单数据
  2.     const navData = [
  3.         {
  4.           id: 1,
  5.           img: nav1,
  6.           title: '整租',
  7.           path: '/house'
  8.         },
  9.         {
  10.           id: 2,
  11.           img: nav2,
  12.           title: '合租',
  13.           path: '/house'
  14.         },
  15.         {
  16.           id: 3,
  17.           img: nav3,
  18.           title: '地图找房',
  19.           path: '/map'
  20.         },
  21.         {
  22.           id: 4,
  23.           img: nav4,
  24.           title: '去出租',
  25.           path: '/rent/add'
  26.         }
  27.       ]
复制代码
3、编写页面内容:
  1.     // 渲染导航菜单
  2.     function renderNav(data, onClick) {
  3.         return (<div className='home-nav'>
  4.             {data.map((item) => {
  5.                 return <div className='home-nav-item' key={item.id} onClick={() => onClick(item)}>
  6.                     <img src={item.img} alt=''></img>
  7.                     <p>{item.title}</p>
  8.                 </div>
  9.             })}
  10.         </div>)
  11.     }
复制代码
4、调解 css 样式结构:
  1.     /* 导航菜单 */
  2.     .home-nav {
  3.         display: flex;
  4.         margin: 16px 0;
  5.     }
  6.     .home-nav-item {
  7.         flex-grow: 1;
  8.         text-align: center;
  9.     }
  10.     .home-nav-item img {
  11.         width: 48px;
  12.     }
  13.     .home-nav-item p {
  14.         font-size: 14px;
  15.         margin: 0;
  16.     }
复制代码
5、调用渲染方法:
  1.             {/* 导航菜单 */}
  2.             { renderNavs(navData, item => navigate(item.path)) }
复制代码
轮播图的问题

由于动态加载数据,有了数据才去渲染轮播图,轮播图从无到有导致轮播图下方的内容会产生一个从上被挤到下面的现象。
办理办法就是在轮播图的外层加一个div,给这个div设置高度:
  1.     // 渲染轮播图
  2.     function renderSwiper(data, indexChange, indexClick) {
  3.         return <div className='swiper'>
  4.             {data && <Swiper
  5.             loop
  6.             autoplay
  7.             onIndexChange={ indexChange }
  8.             >
  9.                 {data.body.map((item, index) => (
  10.                     <Swiper.Item key={index}>
  11.                         <div
  12.                         className='content'
  13.                         onClick={ (e) => indexClick(index, e) }
  14.                         >
  15.                             <img src={'http://127.0.0.1:8080' + item.imgSrc} style={{width: '100%'}} alt=''></img>
  16.                         </div>
  17.                     </Swiper.Item>
  18.                 ))}
  19.             </Swiper>}
  20.         </div>
  21.     }
  22.     /* 轮播图 css */
  23.     .swiper {
  24.         height: 212px;
  25.     }
复制代码
Sass的使用



  • 打开脚手架文档,找到添加Sass样式
  • 安装Sass: npm i sass 或 yarn add sass
  • 创建后缀名为.scss 大概 .sass 的样式文件
  • 在组件中导入Sass样式
修改 Home.css 为 Home.scss 文件,一并修改 Home 组件的导入 import './Home.scss',并修改 导航菜单 为如下样式:
  1.     /* 导航菜单 */
  2.     .home-nav {
  3.         display: flex;
  4.         margin: 16px 0;
  5.         .home-nav-item {
  6.             flex-grow: 1;
  7.             text-align: center;
  8.             img {
  9.                 width: 48px;
  10.             }
  11.             p {
  12.                 font-size: 14px;
  13.                 margin: 0;
  14.             }
  15.         }
  16.     }
复制代码
租房小组

根据当前地理位置展示不同小组信息,需要后台接口根据用户找房数据,推荐用户最感爱好的内容(正常的逻辑是我们先获取到用户当前定位的信息,把信息发送给后台,后台根据定位信息获取对应的内容),前端只需要展示数据。
数据获取

在 Home 组件中调用接口获取数据:
  1.         // 获取租房小组数据
  2.         const { data: groupData } = useData.get('/home/groups', {params: {area: 'AREA%7C88cff55c-aaa4-e2e0'}})
  3.         console.log('groupData: ', groupData);
复制代码
页面结构

1、打开 antd-mobile 组件库的 Grid 组件文档,复杂核心代码并调解,封装为渲染函数:
  1.     // 渲染租房小组
  2.     function renderGroup(data) {
  3.         return <div className='group'>
  4.             <div className='top'>
  5.                 <div className='name'>租房小组</div>
  6.                 <div className='more'>更多</div>
  7.             </div>
  8.             <Grid columns={2} gap={[32, 16]}>
  9.                 {data && data.body.map((item) => {
  10.                     return <Grid.Item key={item.id}>
  11.                         <div className='item'>
  12.                             <div className='left'>
  13.                                 <div className='title'>{item.title}</div>
  14.                                 <div className='desc'>{item.desc}</div>
  15.                             </div>
  16.                             <div className='right'>
  17.                                 <img className='picture' src={`http://127.0.0.1:8080${item.imgSrc}`} alt=''></img>
  18.                             </div>
  19.                         </div>
  20.                     </Grid.Item>
  21.                 })}
  22.             </Grid>
  23.         </div>
  24.     }
复制代码
2、css 样式结构:
  1.     // 租房小组
  2.     .group {
  3.         margin: 8px 0;
  4.         .top {
  5.             display: flex;
  6.             justify-content: space-between;
  7.             margin: 16px;
  8.             .name {
  9.                 font-size: 15px;
  10.                 font-weight: bold;
  11.             }
  12.             .more {
  13.                 font-size: 14px;
  14.                 color: #999999;
  15.             }
  16.         }
  17.         .adm-grid {
  18.             margin: 8px 16px;
  19.             .adm-grid-item {
  20.                 height: 75px;
  21.                 .item {
  22.                     text-align: center;
  23.                     height: 100%;
  24.                     display: flex;
  25.                     justify-content: space-between;
  26.                     text-align: center;
  27.                     padding: 0 8px;
  28.                     .left {
  29.                         display: flex;
  30.                         flex-direction: column;
  31.                         justify-content: center;
  32.                         .title {
  33.                             font-size: 13px;
  34.                             font-weight: bold;
  35.                             margin-bottom: 4px;
  36.                         }
  37.                         .desc {
  38.                             font-size: 12px;
  39.                             color: #999999;
  40.                         }
  41.                     }
  42.                     .right {
  43.                         display: flex;
  44.                         flex-direction: column;
  45.                         justify-content: center;
  46.                         .picture {
  47.                             width: 55px;
  48.                             height: 53px;
  49.                         }
  50.                     }
  51.                 }
  52.             }
  53.         }
  54.     }
复制代码
3、在 Home 组件中调用渲染函数:
  1.             {/* 租房小组 */}
  2.             { renderGroup(groupData)}
复制代码
最新资讯

略……(同租房小组)
办理内容被 TabBar 压住的问题

1、在 App 组件中将 Outlet 路由占位包裹在一个 div 中:
  1.         <div className='app-content'>
  2.           <Outlet></Outlet>
  3.         </div>
复制代码
2、调解相应样式,设置 app 底部 49 像素的内边距,让 app-content 超出父元素的内容滚动表现:
  1.     #root {
  2.       height: 100%;
  3.     }
  4.     .app {
  5.       height: 100%;
  6.       padding-bottom: 49px;
  7.     }
  8.     .app-content {
  9.       height: 100%;
  10.       overflow: scroll;
  11.     }
复制代码
顶部搜索功能

1、干系结构:
  1.     // 渲染顶部搜索
  2.     function renderHeaderSearch(cityName, onClickLoction, onClickSearch, onClickMap) {
  3.         return <div className='headerSearch'>
  4.             <div className='search'>
  5.                 <div className='location' onClick={onClickLoction}>
  6.                     <span className="name">{cityName}</span>
  7.                     <i className="iconfont icon-arrow" />
  8.                 </div>
  9.                 <div className='form' onClick={onClickSearch}>
  10.                     <i className="iconfont icon-seach" />
  11.                     <span className="text">请输入小区或地址</span>
  12.                 </div>
  13.             </div>
  14.             <div className="iconfont icon-map" onClick={onClickMap}></div>
  15.         </div>
  16.     }
复制代码
2、css 样式结构:
  1.     // 顶部搜索
  2.     .headerSearch {
  3.         position: absolute;
  4.         padding: 0 16px;
  5.         width: 100%;
  6.         height: 44px;
  7.         top: 34px;
  8.         display: flex;
  9.         justify-content: space-between;
  10.         align-items: center;
  11.         .search {
  12.             height: 100%;
  13.             padding: 0 8px;
  14.             font-size: 14px;
  15.             border-radius: 3px;
  16.             background-color: white;
  17.             margin-right: 8px;
  18.             flex-grow: 1;
  19.             display: flex;
  20.             align-items: center;
  21.             .location {
  22.                 i {
  23.                     color: #7f7f80;
  24.                     font-size: 12px;
  25.                     margin-left: 2px;
  26.                 }
  27.             }
  28.             .form {
  29.                 margin-left: 24px;
  30.                 color: #9c9fa1;
  31.                 flex-grow: 1;
  32.                 display: flex;
  33.                 span {
  34.                     margin-left: 8px;
  35.                 }
  36.             }
  37.         }
  38.         .icon-map {
  39.             font-size: 25px;
  40.             color: white;
  41.         }
  42.     }
复制代码
3、在 Home 组件中调用渲染函数:
  1.             {/* 顶部搜索 */}
  2.             { renderHeaderSearch('天津', () => navigate('/cityList'), () => navigate('/search'), () => navigate('/map')) }
复制代码
定位干系

H5中地理定理定位API

在 Web 应用程序中获取地理位置(文档)
地理位置API 允许用户向 Web应用程序提供他们的位置,出于隐私思量,报告地理位置前先会哀求用户许可,地理位置的API是通过 navigator.geolocation 对象提供,通过getCurrentPosition方法获取。
获取到的地理位置跟 GPS、IP地址、WIFI和蓝牙的MAC地址、GSM/CDMS的ID有关,好比:手机优先使用GPS定位,条记本等最准确的是定位是WIFI。
  1.     navigator.geolocation.getCurrentPosition(position => {
  2.     // position对象表示当前位置信息
  3.     // 常用: latitude 纬度 / longitude 经度
  4.     // 知道: accuracy 经纬度的精度 / altitude 海拔高度 / altitudeAccuracy 海拔高度的精
  5.     度 / heading 设备行进方向 / speed 速度
  6.     })
复制代码
百度舆图API

H5的地理位置API只能获取到对应经纬度信息,在实际开发中,会使用百度舆图/高德舆图来完成地理位置的干系功能。
1、参照百度舆图文档,注册百度开发者账号,申请对应的AK
2、在 index.html 中引入百度舆图 API 文件,替换自己申请好的密钥:
  1.     <script type="text/javascript" src="https://api.map.baidu.com/api?v=1.0&type=webgl&ak=你的密钥"></script>
复制代码
3、新建 Map 组件文件,创建舆图容器等根本结构,并参照文档创建舆图:
  1.     import { useEffect } from "react";
  2.     import './Map.scss'
  3.     export default function Map() {
  4.         // 创建地图
  5.         useEffect(() => {
  6.             var map = new window.BMapGL.Map("container");          // 创建地图实例
  7.             var point = new window.BMapGL.Point(116.404, 39.915);  // 创建点坐标
  8.             map.centerAndZoom(point, 15);                 // 初始化地图,设置中心点坐标和地图级别
  9.             map.enableScrollWheelZoom(true);     //开启鼠标滚轮缩放
  10.             return () => map = null
  11.         }, [])
  12.         return <div className="map">
  13.             <div id="container"></div>
  14.         </div>
  15.     }
复制代码
4、css 样式结构:
  1.     .map {
  2.         height: 100%;
  3.         #container {
  4.             height: 100%;
  5.         }
  6.     }
复制代码
5、在 index.js 中配置舆图页面的路由:
  1.             <Route path='/map' element={<Map></Map>}></Route>
复制代码
获取顶部搜索城市信息

1、通过IP定位获取到当前城市名称,调用服务器的接口,换取项目中的城市信息:
  1.         // 百度地图 IP 定位,转换城市数据
  2.         const [ city, setCity ] = useState(null);
  3.         useEffect(() => {
  4.             var ignore = false
  5.             var localCity = new window.BMapGL.LocalCity();
  6.             localCity.get((result) => {
  7.                 if (!ignore) {
  8.                     console.log('LocalCity:', result);
  9.                     axios.get('area/info?name=' + result.name).then((cityData) => {
  10.                         if (!ignore) {
  11.                             console.log('cityData:', cityData);
  12.                             setCity(cityData.body.label)
  13.                         }
  14.                     })
  15.                 }
  16.             });
  17.             return () => ignore = true
  18.         }, [])
复制代码
2、修改顶部搜索栏渲染方法的调用,在城市信息获取之前使用 -- 占位符:
  1.             {/* 顶部搜索 */}
  2.             { renderHeaderSearch(city ? city : '--', () => navigate('/cityList'), () => navigate('/search'), () => navigate('/map')) }
复制代码
城市选择模块

顶部导航栏



  • 打开antd-mobile 组件库的NavBar 导航栏组件 文档
  • 从文档中拷贝组件示例代码到项目中,让其正确运行
  • 修改导航栏样式和结构
1、引入 组件库:
  1.     import { NavBar } from 'antd-mobile'
  2.     import { useNavigate } from "react-router-dom";
复制代码
2、拷贝并修改代码结构:
  1.     function CityList() {
  2.         const navigate = useNavigate()
  3.         return (<div className='city-list'>
  4.             {/* 导航栏 */}
  5.             <NavBar style={{
  6.                 '--height': '44px',
  7.                 '--border-bottom': '1px #eee solid',
  8.                 'color': '#333',
  9.                 'backgroundColor': '#f6f5f6'
  10.               }} backIcon={<i className='iconfont icon-back'></i>} onBack={() => { navigate(-1)
  11.             }}>城市列表</NavBar>
  12.         </div>)
  13.     }
复制代码
3、新建并导入样式文件:
  1.     import './CityList.scss'
复制代码
4、设置相应的样式:
  1.     .city-list {
  2.         padding-top: 44px;
  3.         width: 100%;
  4.         height: 100%;
  5.         // 导航栏样式
  6.         .adm-nav-bar {
  7.             margin-top: -44px;
  8.         }
  9.         .adm-nav-bar-title {
  10.             color: #333;
  11.         }
  12.     }
复制代码
城市列表

获取处理数据

1、导入自定义获取数据的 HOOK import useData from '../utils/useData',根据接口文档提供的url举行网络哀求,获取到相应的数据信息:
  1.         // 获取城市列表数据
  2.         const { data: cityData } = useData.get('/area/city', {params:{'level': '1'}})
  3.         console.log('cityData: ', cityData);
复制代码
2、需要把服务器返回的数据举行格式化处理,可以通过首字母来举行城市的定位,以是需要把格式转换成以下格式:
  1.     // 接口返回的数据格式:
  2.     [{ "label": "北京", "value": "", "pinyin": "beijing", "short": "bj" }]
  3.     // 渲染城市列表的数据格式为:
  4.     { a: [{}, {}], b: [{}, ...] }
  5.     // 渲染右侧索引的数据格式为:
  6.     ['a', 'b']
复制代码
3、封装一个函数,来处理这个数据:
  1.     // 城市列表数据处理
  2.     function cityDataHandle(data) {
  3.         if (data && data.body && Array.isArray(data.body) && data.body.length > 0) {
  4.             // 有数据
  5.             // 键是首字母,值是一个数组:对应首字母的城市信息
  6.             const cityList = {}
  7.             data.body.forEach(element => {
  8.                 const firstL = element.short[0]
  9.                 if (cityList[firstL]) {
  10.                     cityList[firstL].push(element)
  11.                 } else {
  12.                     cityList[firstL] = [element]
  13.                 }
  14.             });
  15.             const result = { cityList, cityKeys: Object.keys(cityList).sort() }
  16.             return result
  17.         } else {
  18.             return {}
  19.         }
  20.     }
复制代码
4、调用函数,来格式化数据:
  1.         // 城市列表数据处理
  2.         const { cityList, cityKeys } = cityDataHandle(cityData)
复制代码
获取热门数据

导入所需 HOOK import { useEffect, useState } from "react";,获取数据并添加到 cityList和cityKeys中,留意,对象内里的属性是无序的,可以直接插入,但是数组是有序的需要添加到前面:
  1.         // 获取热门城市数据
  2.         const { data: hotData } = useData.get('/area/hot')
  3.         console.log('hotData: ', hotData);
  4.         if (cityList && cityKeys && hotData && hotData.body && Array.isArray(hotData.body) && hotData.body.length > 0) {
  5.             cityList['hot'] = hotData.body
  6.             cityKeys.unshift('hot')
  7.         }
复制代码
获取当前城市信息

将获取定位城市的代码封装到一个函数中,哪个页面需要获取定位城市,直接调用该方法即可:


  • 在utils目次中,创建一个文件,在这个文件中举行封装
  • 创建而且导出获取定位城市的函数 getCurrentCity
  • 判断localStorage中是否有定位信息
  • 如果没有,我们通过获取定位信息来获取当前定位城市,获取完了需要存到本地存储中
  • 如果有,直接使用就好
  1.     import axios from "axios";
  2.     export default function requestCurrentCity() {
  3.         // 获取本地存储中是否有
  4.         const localCity = localStorage.getItem('localCity')
  5.         console.log('localCity', localCity);
  6.         if (localCity) {
  7.             // 如果有,返回城市信息就好,返回一个成功的promis对象即可
  8.             return Promise.resolve(JSON.parse(localCity))
  9.         } else {
  10.             return new Promise((resolve, reject) => {
  11.                 var localCity = new window.BMapGL.LocalCity();
  12.                 localCity.get(async (result) => {
  13.                     console.log('LocalCity:', result);
  14.                     try {
  15.                         const city = await axios.get('area/info?name=' + result.name)
  16.                         console.log('city: ', city);
  17.                         
  18.                         if (city.status === 200) {
  19.                             localStorage.setItem('localCity', JSON.stringify(city.body))
  20.                             resolve(city.body)
  21.                         } else {
  22.                             console.error(city.description);
  23.                             throw new Error(city.description);
  24.                         }
  25.                     } catch (error) {
  26.                         reject(error)
  27.                     }
  28.                 });
  29.             })
  30.         }
  31.     }
复制代码
将定位的城市信息添加到 cityList和cityIndex中:
  1.         // 获取当前城市
  2.         const [currentCity, setCurrentCity] = useState(null)
  3.         useEffect(() => {
  4.             let ignore = false
  5.             requestCurrentCity().then((data) => {
  6.                 if (!ignore) {
  7.                     setCurrentCity(data)
  8.                 }
  9.             })
  10.             return () => ignore = true
  11.         }, [])
  12.         if (currentCity && cityList) {
  13.             cityList['#'] = [currentCity]
  14.             cityKeys.unshift('#')
  15.         }
  16.         console.log('cityList: ', cityList);
  17.         console.log('cityKeys: ', cityKeys);
复制代码
长列表性能优化

在展示大型列表和表格数据的时间(城市列表、通讯录、微博等),会导致页面卡顿,滚动不流通等性能问题,这样就会导致移动装备耗电加快,影响移动装备的电池寿命
产生性能问题的原因:大量DOM节点的重绘和重排
优化方案:懒渲染、可视区域渲染
懒加载,常见的长列表优化方案,常见于移动端:


  • 原理:每次只渲染一部分,等渲染的数据即将滚动完时,再渲染下面部分
  • 长处:每次渲染一部分数据,速度快
  • 缺点:数据量大时,页面中依然存在大量DOM节点,占用内存过多,低落浏览器渲染性能,导致页面卡顿
  • 使用场景:数据量不大的情况下
可视区渲染(React-virtualized):


  • 原理:是只渲染页面可视区域的列表项,非可视区域的数据 完全不渲染(预加载前面几项和背面几项) ,在滚动列表时动态更新列表项
  • 使用场景: 一次性展示大量数据的情况
react-virtualized 渲染城市列表

react-virtualized 是React组件,用来高效渲染大型列表和表格数据,GitHub地址: react-virtualized
1、安装: import i react-virtualized
2、在项目入口文件 index.js 中导入样式文件 import "react-virtualized/styles.css";
3、打开 文档, 点击List组件,进入List的文档中,拷贝示例中渲染每一行的代码到项目中并按需求修改:
  1.         // 渲染每一行
  2.         function rowRenderer({
  3.                 index, // 索引号
  4.                 isScrolling, // 当前项是否正在滚动中
  5.                 isVisible, // 当前项在List中是可见的
  6.                 key, // 渲染数组中行的唯一键
  7.                 parent, // 对父List(实例)的引用
  8.                 style, // 重点属性:一定要给每一个行数添加该样式
  9.             }){
  10.             let title = cityKeys[index]
  11.             const citys = cityList[title]
  12.             switch (title) {
  13.                 case '#':
  14.                     title = '当前定位'
  15.                     break;
  16.                 case 'hot':
  17.                     title = '热门城市'
  18.                     break
  19.                 default:
  20.                     break;
  21.             }
  22.             
  23.             return (
  24.                 <div key={key} style={style} className='city'>
  25.                     <div className='title'>{title}</div>
  26.                     {
  27.                         citys.map((item, i) => {
  28.                             return <div className='name' key={item.value}>{item.label}</div>
  29.                         })
  30.                     }
  31.                 </div>
  32.             );
  33.         }
复制代码
4、渲染城市列表,使用 AutoSizer 组件来调解子元素的宽高


  • 导入 AutoSizer、List 组件 import { List, AutoSizer } from "react-virtualized";
  • 通过 render-props 模式,获取到AutoSizer 组件袒露的 width 和 height 属性
  • 设置List组件的 width 和 height 属性
  1.             {/* 城市列表 */}
  2.             { cityKeys && <AutoSizer>
  3.                 { ({width, height}) => {
  4.                     return <List
  5.                         width={width}
  6.                         height={height}
  7.                         rowCount={cityKeys.length}
  8.                         rowHeight={({index}) => {
  9.                             console.log('index: ', index);
  10.                             const key = cityKeys[index]
  11.                             const section = cityList[key]
  12.                             console.log('section: ', section);
  13.                            
  14.                             return 20 + 44*section.length
  15.                         }}
  16.                         rowRenderer={rowRenderer}
  17.                     />
  18.                 } }
  19.             </AutoSizer> }
复制代码
5、为城市列表设置样式:
  1.     // 城市列表样式
  2.     .city {
  3.         .title {
  4.             height: 20px;
  5.             background-color: #e5e5e5;
  6.             padding: 0 12px;
  7.             font-size: 12px;
  8.             line-height: 20px;
  9.         }
  10.         .name {
  11.             height: 44px;
  12.             padding: 0 16px;
  13.             font-size: 14px;
  14.             line-height: 44px;
  15.         }
  16.     }
复制代码
渲染右侧索引列表

1、添加状态 activeIndex,用来指定当前高亮的索引:
  1.         // 高亮索引
  2.         const [activeIndex, setActiveIndex] = useState(0)
复制代码
2、遍历cityIndex,渲染索引列表,将索引 hot 替换成 热:
  1.             {/* 右侧索引 */}
  2.             { cityKeys && <ul className='city-index'>
  3.                 {cityKeys.map((item, index) => <li className={activeIndex === index ? 'active' : ''} key={item}>{item === 'hot' ? '热' : item}</li>)}
  4.             </ul> }
复制代码
3、为索引列表添加样式:
  1.     // 城市索引列表样式
  2.     .city-index {
  3.         position: absolute;
  4.         right: 8px;
  5.         height: 90%;
  6.         list-style: none;
  7.         margin: 0;
  8.         padding: 5px;
  9.         text-align: center;
  10.         display: flex;
  11.         flex-direction: column;
  12.         justify-content: space-around;
  13.         .active {
  14.             color: #fff;
  15.             background-color: #21b97a;
  16.             width: 15px;
  17.             height: 15px;
  18.             font-size: 12px;
  19.             text-align: center;
  20.             line-height: 15px;
  21.             border-radius: 100%;
  22.         }
  23.     }
复制代码
4、城市索引列表高亮
给 List 组件添加onRowsRendered配置项,用于获取当火线表渲染的行信息,在内里就会有相应信息,通过参数 startIndex 获取到 起始行对应的索引号。判断 startIndex 和 activeIndex 不同时间,更新状态 activeIndex 为 startIndex:
  1.                         onRowsRendered={({startIndex}) => {
  2.                             console.log('startIndex: ', startIndex);
  3.                            
  4.                             if (startIndex !== activeIndex) {
  5.                                 setActiveIndex(startIndex)
  6.                             }
  7.                         }}
复制代码
5、点击索引置顶该索引城市
引入 useRef import { useRef } from "react";,并在组件顶部初始化 ref:
  1.         // 列表 ref
  2.         const listRef = useRef(null)
复制代码
将创建好的ref对象,添加为List组件的ref属性,设置List组件的scrollToAlignment配置项值为start,保证点击行出现在页面顶部:
  1.                     <List
  2.                         ……
  3.                         scrollToAlignment='start'
  4.                         ref={listRef}
  5.                     />
复制代码
给索引列表绑定点击事件,在点击事件中。通过 index 获取到当前项索引号通过 ref 的 current 属性,获取到组件实例,再调用组件的scrollToRow方法让List组件滚动到指定行:
  1.             {/* 右侧索引 */}
  2.             { cityKeys && <ul className='city-index'>
  3.                 {cityKeys.map((item, index) => <li className={activeIndex === index ? 'active' : ''} key={item} onClick={() => {
  4.                     listRef.current.measureAllRows()
  5.                     listRef.current.scrollToRow(index)
  6.                 }}>{item === 'hot' ? '热' : item}</li>)}
  7.             </ul> }
复制代码
对于点击索引无法正确定位的问题,在List组件调用 measureAllRows 方法之前调用 measureAllRows,提前盘算高度来办理。
切换城市



  • 给城市列表项绑定事件
  • 判断当前城市是否有房源数据,只有热门城市有房源数据
  • 如果有房源数据,则保持当前城市数据到本地缓存中,并返回上一页
  • 如果没有房源数据,则使用antd-mobile中的 Toast 组件提示用户:改城市暂无房源数据,不执行任何操纵
  1.         // 渲染每一行
  2.         function rowRenderer({
  3.                 index, // 索引号
  4.                 isScrolling, // 当前项是否正在滚动中
  5.                 isVisible, // 当前项在List中是可见的
  6.                 key, // 渲染数组中行的唯一键
  7.                 parent, // 对父List(实例)的引用
  8.                 style, // 重点属性:一定要给每一个行数添加该样式
  9.             }){
  10.             let title = cityKeys[index]
  11.             const citys = cityList[title]
  12.             switch (title) {
  13.                 case '#':
  14.                     title = '当前定位'
  15.                     break;
  16.                 case 'hot':
  17.                     title = '热门城市'
  18.                     break
  19.                 default:
  20.                     break;
  21.             }
  22.             
  23.             return (
  24.                 <div key={key} style={style} className='city'>
  25.                     <div className='title'>{title}</div>
  26.                     {
  27.                         citys.map((item, i) => {
  28.                             return <div className='name' key={item.value} onClick={() => {
  29.                                 const hotList = cityList['hot']
  30.                                 let contain = false
  31.                                 for (const i in hotList) {
  32.                                     const v = hotList[i]
  33.                                     if (v.label === item.label) {
  34.                                         contain = true
  35.                                         break
  36.                                     }
  37.                                 }
  38.                                 if (contain) {
  39.                                     // 热门城市才有房源数据
  40.                                     localStorage.setItem('localCity', JSON.stringify({'label': item.label, 'value': item.value}))
  41.                                     navigate(-1)
  42.                                 } else {
  43.                                     Toast.show({ content: '该城市暂无房源数据', duration: 2000 })
  44.                                 }
  45.                             }}>{item.label}</div>
  46.                         })
  47.                     }
  48.                 </div>
  49.             );
  50.         }
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
继续阅读请点击广告

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

嚴華

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表