typescript - Angular/NGRX: พฤติกรรมแปลก ๆ กับ entity และ selectAll?
seletAll จาก getSelectors() จะเรียกเหตุการณ์โดยไม่เปลี่ยนแปลงไปยังสโตร์ฟีเจอร์ของตัวเอง แต่เมื่อสโตร์รากเปลี่ยนแปลง
เปิดเดโม่แล้วคลิกที่ปุ่ม ปุ่มจะส่งการเปลี่ยนแปลงไปยัง root store แต่ selectAll จาก feature store ก็จะเรียกเหตุการณ์นี้เช่นกัน:
https://stackblitz.com/edit/angular-ngrx-test-123654789-a7js8p?file=src%2Fapp%2Ffeatures%2Fbar.component.ts
พฤติกรรมนี้เกิดขึ้นเฉพาะเมื่อ seletAll ถูกใช้ในตัวเลือกอื่นที่ยอมรับ props เป็นพารามิเตอร์
seletAll ควรเรียกใช้อีเวนต์เฉพาะเมื่อมีการเปลี่ยนแปลงเกิดขึ้นในฟีเจอร์สโตร์เท่านั้น
นี่คือ selectors:
export const selectBarStore = createFeatureSelector<State>('barStore');
export const selectBarState = createSelector(
selectBarStore,
(state: State) => state ? state.bar : null
);
export const { selectEntities, selectAll } = adapter.getSelectors(selectBarState);
export const selectBarById = createSelector(
selectAll,
(itemEntities: Bar[], props: {id: number}) =>
itemEntities ? itemEntities.filter(element => element.id === props.id) : []
);
อัพเดท 1:
ฉันได้เปิดปัญหาหนึ่งใน GitHub ของ ngrx ด้วย https://github.com/ngrx/platform/issues/2707
นักพัฒนา ngrx พูด
ฉันไม่แน่ใจว่านี่เป็นบั๊กหรือไม่ และถ้ามันเป็นบั๊ก จะต้องแก้ไขอย่างไร สาเหตุหลักมาจากตัวเลือก props ซึ่งใช้ instance selectAll เดียวกัน (เพราะมันส่ง props ลงไปที่ selectAll)
อัปเดต 2
วิธีแก้ปัญหาคือทำให้ตัวเลือกเป็นโรงงานและอย่าส่งพารามิเตอร์ props:
ก่อน
export const selectBarById = createSelector(
selectAll,
(itemEntities: Bar[], props: {id: number}) =>
itemEntities ? itemEntities.filter(element => element.id === props.id) : []
);
หลังจาก
export const selectBarById = (id: number) => createSelector(
selectAll,
(itemEntities: Bar[]) =>
itemEntities ? itemEntities.filter(element => element.id === id) : []
);
คำถามหลักคือ: นี่เป็นบั๊กของ NGRX หรือฉันทำอะไรผิด?
