鸿蒙开发刷新单个item会闪一下
首先我用的是懒加载方式,改变某位数据后我调listener.onDataChange(index),发现item的改动是变了,但是item也闪了一下。
先分析为什么item会闪一下
其他是因为item上有图片,加载的网络图。你onDataChange(index)时,它会重新加载这一item,自然图片也重新加载,因为是网络图,加载需要时间,所以就闪了一下
解决方案1:用@ObjectLink和@Observed配合使用
好处: 用了它,你不用调onDataChange(index),它也会改动成功,并且不闪
不好: 它只支持类,并且每个对象都得new 进去
关键代码示例如下:
1、bean类必须加@Observed
@Observed
export class HomeBaseListBean{
authMsg?:string
jobAuthStatus?:boolean
videoAuthStatus?:boolean
vipStatus?:boolean
checkIsLove?:boolean
constructor(authMsg?:string,
jobAuthStatus?:boolean,
videoAuthStatus?:boolean,
vipStatus?:boolean,
checkIsLove?:boolean,
2、必须是在@Component组件里面用
@Component
export struct HomeWaterFallItemComponent {
// 继续用ObjectLink这样不用刷新整个item,避免闪烁
@ObjectLink userBean:HomeBaseListBean
假设里面组件触发改变
Image(this.userBean.checkIsLove?$r('app.media.ic_heart_on_formal_three'):$r('app.media.ic_heart_off_formal_three'))
.width(24)
.height(24)
.padding(4)
.onClick(()=>{
CommonViewModel.postLove(this.userBean.resume?.id!,this.userBean.resume?.sex?this.userBean.resume?.sex:0,true,(loveState)=>{
this.userBean.checkIsLove = loveState
})
})
这样设置它就会变了,并且不会触发到其他组件重新加载的。 3、给dataList赋值时必须new bean**(这是很关键的)**
HomeViewModel.getHangAroundDatas(this.mediator, this.touristSex, (result: HomeBaseListBean[]) => {
let list :HomeBaseListBean[] = []
result.forEach((value,index) =>{
list.push(new HomeBaseListBean(value.authMsg,
value.jobAuthStatus,
value.videoAuthStatus,
value.vipStatus,
value.checkIsLove,
value.headImg,
value.resume,
value.authJob,
value.imAccount,
value.showHomeLabel,
value.imageList,
value.isTop,
value.isOutReachNewest
))
})
this.mediator.finishRefresh(true, false, list)
解决方案2:在@Component组件中加@State状态
好处:不用像方案1那样改动这么多 坏处:它只是改变它当前的Component,它数据源其实是没有改变的。你要自己再处理数据源,如果你要用到数据源它的改动 关键示例代码如下: 1、bean在@Component组件中加@State状态
@Component
export default struct CardComponent {
// 卡片数据,默认初始化
@State userInfo: UserDataBean = {};
2、改变bean的状态代码
Stack(){
Row({space:8}){
Image(this.userInfo.checkIsLove?$r('app.media.ic_heart_on'):$r('app.media.ic_heart_off'))
.width(19)
.height(19)
Text($r('app.string.beckoning'))
.fontSize(18)
.fontColor($r('app.color.color_black'))
}
.padding({
left:16,
right:16,
})
.borderWidth(0.5)
.borderColor($r('app.color.color_black'))
.borderRadius(40)
.margin({
top:12
})
.height(36)
.onClick(()=>{
if (this.cardIndex !== this.showingCard) {
return;
}
// 点击心动
if (!InfoCheckUtils.isTourist(true) && InfoCheckUtils.isFormalUser() &&
InfoCheckUtils.checkResumeStateDialog() && InfoCheckUtils.checkIdentityStateDialog() && !InfoCheckUtils.isNeedJobAuth(this.isJobShow)) {
if (this.isRecommend && MMKVUtil.getVipState() === 0) {
Router.pushBuyVipPage(PathType.VIP_PATH_2,true,this.recommendNoVip)
} else {
CommonViewModel.postLove(this.userInfo.resume?.id!,this.userInfo.resume?.sex?this.userInfo.resume?.sex:0,false,(loveState)=>{
this.userInfo.checkIsLove = loveState
})
}
}
})
}
.width('100%')
.layoutWeight(1)
其实就当它是state来用,数据源没变的哦,这个别忘了
有鸿蒙开发bug或者需求都可以私信我,我每天看私信的