HarmonyOS-基础之ForEach注意的问题
注意避坑:
- (item, index) => index + JSON.stringify(item) 默认写法,不会丢失下标的顺序,但是修改数据顺序时重新加载了,效率低一点
- (item, index) => JSON.stringify(item) 这种写法效率虽然高一点,但是修饰了下标的顺序
父组件:
import { User } from '../domain/Model'
import Item02 from '../components/Item02'
/**
* forEach列表渲染
* 参数1:遍历的数据列表
* 参数2:创建组件的回调函数
* 参数3:key标识
*/
@Entry
@Component
struct ForEachExample {
@State users: User[] = [
{ id: 1, name: '张三东', age: 28 },
{ id: 2, name: '李四西', age: 21 },
{ id: 3, name: '王五南', age: 35 },
{ id: 4, name: '赵六北', age: 30 }
]
updateProperties() {
this.users[1] = { id: 2, name: '修改后的李四西', age: 23 }
}
updateSort() {
this.users = [this.users[2], this.users[0], this.users[3], this.users[1]]
}
build() {
Column() {
Row() {
ForEach(this.users, (item, index) => {
Item02({ user: item })
.margin({ top: 3 })
.border({ width: 1, color: Color.Blue, radius: 5 })
}, (item, index) => JSON.stringify(item))
}.height(200)
Button('Update-修改内部属性').onClick(() => {
this.updateProperties()
}).margin({ bottom: 10 })
Button('Update-修改数组顺序').onClick(() => {
this.updateSort()
}).margin({ bottom: 10 })
Row() {
/**
* 注意避坑:
*
* (item, index) => index + JSON.stringify(item) 默认写法,不会丢失下标的顺序,但是修改数据顺序时重新加载了,效率低一点
*
* (item, index) => JSON.stringify(item) 这种写法效率虽然高一点,但是修饰了下标的顺序
*/
List({ space: 10 }) {
ForEach(this.users, (user, index) => {
ListItem() {
Row({ space: 10 }) {
Text('--' + Date.now())
Text(index + "")
Text(user.id + "")
Text(user.name)
}
}
}, (item, index) => JSON.stringify(item))
}
}.width('100%').border({ width: 1, color: Color.Red })
}.width("100%")
.border({ width: 1 })
}
}
子组件:
import { User } from '../domain/Model'
@Component
export default struct Item02 {
@ObjectLink user: User
build() {
Column() {
Text(`我是Item02子组件 : \r\n${JSON.stringify(this.user)}`)
.fontColor(Color.Pink)
.height(50)
}.width("100%")
}
}
分类:
HarmonyOS
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
2022-04-10 Elasticsearch入门到进阶