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%")
  }
}
posted @ 2024-04-10 23:06  我也有梦想呀  阅读(225)  评论(0)    收藏  举报