使用 OnPush 策略时,不会重新呈现子组件的视图


@Component({
selector: "parent",
template: `<child [userId]="(userId$ | async)"></child>`,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class ParentCmp implements OnInit {
userId$: BehaviorSubject<string> = new BehaviorSubject<string>(null);
constructor(private activatedRoute: ActivatedRoute) { }
ngOnInit() {
this.activatedRoute.queryParams.subscribe(query => {
//notify child with BehaviorSubject
this.userId$.next(query["userid"])
}
}
}
@Component({
selector: "child",
template: `<div *ngIf="(userState$ | async) && userId">
{{(userState$ | async).user.id)}}
</div>`,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class ChildCmp implements OnChanges {
@Input() userId: string;
private userState$: Observable<User>;
constructor(private store: Store<store.AppState>) { }
ngOnChanges(changes: SimpleChanges) { 
//when it gets userId it starts to track fit user in ngrx store
this.userState$ = this.store
.select(state => state.user-list)                 
.map(userList => userList[this.userId])
.filter(user => !!user);
}
}

子 cmp 从父级 1 获取 userId,并且所需的用户包含在 ngrx 存储 (userList( 中,但子项视图不会重新呈现。当子项的更改检测策略是默认值时,它可以完美地工作。这里可能出了什么问题? 角度 v2.4

如果在ngOnChanges()中更改模型,则需要显式调用更改检测

export class ChildCmp implements OnChanges {
@Input() userId: string;
private userState$: Observable<User>;
constructor(
private store: Store<store.AppState>,
private cdRef:ChangeDetectorRef
) { }
ngOnChanges(changes: SimpleChanges) { 
//when it gets userId it starts to track fit user in ngrx store
this.userState$ = this.store
.select(state => state.user-list)                 
.map(userList => userList[this.userId])
.filter(user => !!user);
this.cdRef.detectChanges();
}
}

或者最好将userStates$设置为可观察对象并保留相同的实例,而不是每次调用ngOnChanges时创建一个新实例:

userId$: Subject<User> = new Subject<User>();
ngOnChanges(changes: SimpleChanges) { 
//when it gets userId it starts to track fit user in ngrx store
this.store
.select(state => state.user-list)                 
.map(userList => userList[this.userId])
.filter(user => !!user)
.subscribe((user) => this.userId.next(user));
}

最新更新