本文主要内容是制作文章列表,实现流程与之前基本相同。因此,在此填写主要的组件、样式和 reducer 代码。
1. 文章列表制作
1.1 List 组件
import React, { Component } from 'react';
import { ListInfo, ListItem } from '../style';
import { connect } from 'react-redux';
class List extends Component {
render() {
const { list } = this.props;
return (
<div>
{list.map((item) => (
<ListItem key={item.get('id')}>
<img className='pic' src={item.get('imgUrl')} alt='' />
<ListInfo>
<h3 className='title'>{item.get('title')}</h3>
<p className='desc'>{item.get('desc')}</p>
</ListInfo>
</ListItem>
))}
</div>
);
}
}
const mapStateToProps = (state) => ({
list: state.getIn(['home', 'articleList']),
});
export default connect(mapStateToProps, null)(List);
1.2 样式
jsxCopy code
export const ListItem = styled.div`
overflow: hidden;
padding: 20px 0;
border-bottom: 1px solid #dcdcdc;
.pic {
display: block;
width: 125px;
height: 100px;
float: right;
}
`;
export const ListInfo = styled.div`
width: 500px;
float: left;
.title {
line-height: 27px;
font-size: 18px;
font-weight: bold;
color: #333;
}
.desc {
line-height: 24px;
font-size: 13px;
color: #999;
}
`;
1.3 reducer
const defaultState = fromJS({
topicList: [
{
id: 1,
title: '社会热点',
imgUrl:
'https://upload-images.jianshu.io/upload_images/1741702-7d340c9913d5ada8.jpg?imageMogr2/auto-orient/strip|imageView2/2/w/424/format/webp',
},
{
id: 2,
title: '手绘',
imgUrl:
'https://upload-images.jianshu.io/upload_images/1741702-7d340c9913d5ada8.jpg?imageMogr2/auto-orient/strip|imageView2/2/w/424/format/webp',
},
],
articleList:[{ id:1, title:'Python大佬实战APP抓包,抖音的小姐姐等着我!', desc:'APP抓包 前面我们了解了一些关于 Python 爬虫的知识,不过都是基于 PC 端浏览器网页中的内容进行爬取。现在手机 App 用的越来越多,...', imgUrl:'https://upload-images.jianshu.io/upload_images/13448242-20871e9f865fb242.jpg?imageMogr2/auto-orient/strip|imageView2/2/w/594/format/webp' },{ id:2, title:'Python大佬实战APP抓包,抖音的小姐姐等着我!', desc:'APP抓包 前面我们了解了一些关于 Python 爬虫的知识,不过都是基于 PC 端浏览器网页中的内容进行爬取。现在手机 App 用的越来越多,...', imgUrl:'https://upload-images.jianshu.io/upload_images/13448242-20871e9f865fb242.jpg?imageMogr2/auto-orient/strip|imageView2/2/w/594/format/webp' },{ id:3, title:'Python大佬实战APP抓包,抖音的小姐姐等着我!', desc:'APP抓包 前面我们了解了一些关于 Python 爬虫的知识,不过都是基于 PC 端浏览器网页中的内容进行爬取。现在手机 App 用的越来越多,...', imgUrl:'https://upload-images.jianshu.io/upload_images/13448242-20871e9f865fb242.jpg?imageMogr2/auto-orient/strip|imageView2/2/w/594/format/webp' }]
});
2. 推荐区域
这部分编写逻辑和上面都是类似的,就不贴出对应代码了
3. 心得
- 组件化思想 在编写 Web 列表页时,建议采用组件化思想,将页面拆分为不同的组件,每个组件只负责特定的功能。组件化的好处在于可以提高代码的可重用性和可维护性,同时也可以使代码结构更加清晰,方便排查问题。
- 样式模块化 样式模块化是一种有效的方法,可以确保 CSS 样式表只适用于特定的组件或页面。建议使用 CSS 预处理器(如 Sass、Less、Stylus)等工具,它们可以帮助你更加有效地管理和组织样式代码,并提供更多的样式特性。
- 数据状态管理 在 Web 列表页中,通常需要管理大量的数据,例如列表数据、筛选条件、分页信息等。建议使用一些数据状态管理库(如 Redux、Mobx)等,可以将数据逻辑与页面组件解耦,使得代码更加清晰和易于维护。
- 前后端分离 前后端分离是现代 Web 开发的主流趋势,前端代码负责渲染页面,后端代码负责提供 API 接口和数据存储等。建议在编写 Web 列表页前端代码时,要充分考虑后端数据接口的设计和使用,确保前后端的交互能够顺畅地进行。
- 性能优化 Web 列表页通常需要渲染大量的数据和组件,因此性能优化是非常重要的。建议在开发过程中要注意减少不必要的 DOM 操作、避免过度渲染和重绘、使用合适的数据缓存等方法,以提高页面性能和用户体验。