NGRX 查找一个对象表单列表并对其进行更新



当用户单击按钮时,我的ngrx/store中有一个对象列表,我想使用对象ID查找该对象并使用我们的ngxr/entities更新相关属性.不知何故,我设法做到了这一点,但我知道这不是正确的方法。

const initialState: TourListState = {
tours: null,
isLoading: false,
error: null
}
const tourListReducer = createReducer(initialState,
...,
...,
...,
...,
on(createTourListSucess, (state) => {
return { ...state, isLoading: false }
}),
on(updateTourList, (state, { tour }) => {
state.tours.find(tourex => tourex.tourId === tour.tourId).coverImage = tour.coverImage;
state.tours.find(tourex => tourex.tourId === tour.tourId).title = tour.title;
state.tours.find(tourex => tourex.tourId === tour.tourId).priceInfo = tour.priceInfo;
state.tours.find(tourex => tourex.tourId === tour.tourId).city = tour.city;
state.tours.find(tourex => tourex.tourId === tour.tourId).countryName = tour.countryName;
return { ...state, isLoading: false }
}),
on(updateTourListSuccess, (state) => {
return { ...state, isLoading: false }
}),
....,
)
export function reducer(state: TourListState | undefined, action: Action) {
return tourListReducer(state, action)
}

您直接修改状态,不建议这样做 - 即使您之后克隆它。

您可以在以下情况下使用地图运算符:

return {
...state,
tours: state.tours.map(t => t.tourId === tourId ? (updateTour) : t) 
}

上面的代码片段循环遍历旅游集合,如果它发现要更新的旅游,它将更新它,否则它只会按原样返回旅游。

另一种解决方案是使用mutableOn(在下面使用 Immer(。

mutableOn(update, (state, { tour }) => {
const entity = state.tours.find(t => t.tourId === tourId)
if (entity) {
entity.foo = tour.foo
entity.bar = tour.bar
}
}),

最新更新