开发中写长列表下拉刷新,因为官方案例太啰里八嗦了,很多杂的东西,对第一次接触的人不太友好,自己摸索了挺长时间,记录一下
const data = [
{
des: '文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题1',
},
{
des: '文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题2',
},
{
des: '文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题3',
},
// {
// des: '文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题1',
// },
// {
// des: '文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题2',
// },
// {
// des: '文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题3',
// },
];
class ArticleList extends React.Component {
constructor(props) {
super(props);
const dataSource = new ListView.DataSource({
rowHasChanged: (row1, row2) => row1 !== row2,
});
this.state = {
dataSource,
isLoading: true,
height: document.documentElement.clientHeight,
dataArr: [],
datas: [],
pageNo: 1,
pageSize: 1,
hasMore: true,
};
}
componentDidMount() {
setTimeout(() => {
this.getData()
}, 600);
}
// 数据请求
getData() {
const dataList = data
// 这里表示上拉加载更多
// 合并state中已有的数据和新增的数据
var dataArr = this.state.dataArr.concat(dataList) //关键代码
this.setState({
pageNo: this.state.pageNo,
dataSource: this.state.dataSource.cloneWithRows(dataArr), // 数据源中的数据本身是不可修改的,要更新datasource中的数据,请(每次都重新)调用cloneWithRows方法
dataArr: dataArr // 保存新数据进state
})
// 判断总如果数据就一页 就不用加载了
if(this.state.pageSize === 1){
this.setState({isLoading: false})
}
}
// 触底加载
onEndReached = (event) => {
if (this.state.isLoading && !this.state.hasMore) {
return;
}
// 每次触底请求一遍数据
setTimeout(()=>{
this.setState({
// isLoading: false,
pageNo: this.state.pageNo + 1, // 加载下一页
}, ()=> {
// 如果大于总数据页数 就停止加载
if(this.state.pageNo > 3){
this.setState({isLoading: false})
return
}
this.getData()
})
}, 2000)
}
render() {
// 在这里循环每条数据 渲染页面
const row = (rowData, sectionID, rowID) => {
// 这里可以自己打印一下 这三个内置的参数,一目了然
return (
<li key={rowData}>
<h3>{rowData.des}</h3>
<div>
<span>2020-10-10</span>
<span>
<img src={images.icon_yueduliang} alt="icon_yueduliang"/>
123
</span>
</div>
</li>
);
};
return (
<div className={style.articleList}>
<ul>
<ListView
dataSource={this.state.dataSource}
renderFooter={() => (<div style={{ padding: 10, textAlign: 'center', fontSize: 13, color: '#C2C2C2' }}>
{this.state.isLoading ? '加载中...' : '没有更多了'}
</div>)}
renderRow={row}
style={{
height: this.state.height,
overflow: 'auto'
}}
// pageSize={5}
scrollRenderAheadDistance={100}
onEndReached={this.onEndReached}
onEndReachedThreshold={10}
/>
</ul>
</div>
);
}
}
讲到底,
关键点就是这几个:
1. 申明一个实例
const dataSource = new ListView.DataSource({
rowHasChanged: (row1, row2) => row1 !== row2,
});
2. 直接调用这个实例的cloneWithRows方法,把要渲染的数据(数组)丢进去
dataSource: this.state.dataSource.cloneWithRows(dataArr)
3. 给组件绑定处理好的dataSource,要渲染什么数据就可以在row里面写,三个参数,主要是第一个参数
<ListView
dataSource={this.state.dataSource}
renderRow={row}
/>