我正在使用angular-redux来创建商店。商店有一个名为'roomListState'的切片,它是一组房间。我有一个容器组件订阅此列表,并创建列表中每个房间的视图,其open属性设置为true。
如果房间中的消息有更新,我使用如下所示的reducer功能更新商店。容器组件订阅房间列表的更新。它将列表(带有rs.open属性)过滤到其打开的房间列表中。每当更改任何房间时,更新开放房间的容器组件列表,从而重新绘制所有打开的房间。
有没有更好的方法来显示开放的房间而不必重绘所有房间? 作为重新创建所有房间的副作用,用户发送消息的房间正在失去焦点。
export interface IAppState {
userState: IUserState;
roomListState: IRoomListState;
}
export interface IRoomListState {
rooms: Array<Room>;
}
//...
// adds an array of messages to a room using a supplied id
function addMessagesToRoom(state: IRoomListState, action: IRoomListAction): IRoomListState {
let newState = { ...state };
let newRooms = [...state.rooms];
newState.rooms = newRooms;
let roomIndex = newRooms.findIndex((r: Room) => r.id === action.roomId);
if (roomIndex === -1) {
console.log('Error: room id not found for message update. State not updated');
return state;
} else {
newRooms[roomIndex] = new Room(state.rooms[roomIndex]);
let newMessages = [...newRooms[roomIndex].messages, ...action.messages];
newRooms[roomIndex].messages = newMessages;
return newState;
}
}
我的容器组件正在订阅状态的roomList切片的更新:
public ngOnInit() {
this.openRooms$ = this.ngRedux.select(['roomListState', 'rooms']).map((rs: Array<Room>) => {
let ors: Array<Room> = [];
rs.forEach((r: Room) => {
if (r.open) {
ors.push(r);
}
});
return ors;
});
this.openRooms$.subscribe((rs: Array<Room>) => {
this.openRooms = rs;
// console.log('Open Rooms List is now: ', this.openRooms);
})