分页加载关键字:
onReachEnd
一、申请网络权限
在 module.json5
文件中,添加网络权限:
json
{
"module": {
...
"requestPermissions": [
{
"name": "ohos.permission.INTERNET",
"usedScene": {
"when": "always"
}
}
]
}
}
二、创建数据结构体
ts
export default class NewsInfo {
title: string = ''
thumbnail: string = ''
publish_time: string = ''
source: string = ''
origin: string = ''
}
ts
import NewsInfo from '../viewmodel/NewsInfo'
export default class NewsData {
code: string = ''
data: NewsInfo[] = []
}
三、封装网络请求
ts
import NewsData from '../viewmodel/NewsData';
import http from '@ohos.net.http';
class NewsModel {
baseURL: string = 'https://china.nba.cn/cms/v1'
pageNo: number = 1
getNewsList(): Promise<NewsData> {
return new Promise((resolve, reject) => {
let httpRequest = http.createHttp()
httpRequest.request(
`${this.baseURL}/news/list?column_id=57&page_size=5&page_no=${this.pageNo}&app_key=tiKB2tNdncnZFPOi&os_type=3&os_version=10.0&app_version=1.0.0&install_id=202111201544&network=wifi&t=1716876416465&device_id=6bdaac33a8df720345a767431e62caf3&channel=nba&sign=48da38cc43775e0efea30a3726328530`,
{
method: http.RequestMethod.GET
}
)
.then(response => {
if (response.responseCode === 200) {
console.log('查询新闻信息成功!', response.result)
resolve(JSON.parse(response.result.toString()))
} else {
console.log('查询新闻信息失败!error:', JSON.stringify(response))
reject('查询新闻信息失败')
}
})
.catch((error: Error) => {
console.log('查询新闻信息失败!error:', JSON.stringify(error))
reject('查询新闻信息失败')
})
})
}
}
const newsModel = new NewsModel()
export default newsModel as NewsModel
四、创建 item 布局
ts
import NewsInfo from '../viewmodel/NewsInfo'
@Component
export default struct NewsItem {
news: NewsInfo = new NewsInfo()
build() {
Column({ space: 5 }) {
Column() {
Image(this.news.thumbnail)
Text(this.news.title)
.fontSize(20)
.fontWeight(FontWeight.Bold)
.ellipsisMode(EllipsisMode.END)
}
.width('100%')
}
}
}
五、实现网络请求分页加载
ts
import NewsInfo from '../viewmodel/NewsInfo'
import NewsItem from '../views/NewsItem'
import NewsModel from '../model/NewsModel'
@Entry
@Component
struct Index {
@State news: NewsInfo[] = []
isLoading: boolean = false
isMore: boolean = true
aboutToAppear(): void {
this.loadNewsInfo()
}
build() {
Column() {
List({ space: 10 }) {
ForEach(this.news, (news: NewsInfo) => {
ListItem() {
NewsItem({ news: news })
}
})
}
.width('100%')
.onReachEnd(() => {
console.log('触底了!')
if (!this.isLoading && this.isMore) {
this.isLoading = true
// 翻页
NewsModel.pageNo++
this.loadNewsInfo()
}
})
}
.width('100%')
.height('100%')
.padding(10)
}
loadNewsInfo() {
NewsModel.getNewsList()
.then(newsData => {
this.news = this.news.concat(newsData.data)
this.isLoading = false
if (!newsData.data || newsData.data.length == 0) {
this.isMore = false
}
})
}
}