在这个@ngrx 效果示例中,下一行中的reduce
函数是做什么的?
const newBookEntities = newBooks.reduce((entities: { [id: string]: Book }, book: Book) => {
return Object.assign(entities, {
[book.id]: book
});
}, {});
不能newBooks
用来代替newBookEntities
吗?
export function reducer(state = initialState, action: book.Actions | collection.Actions): State {
switch (action.type) {
case book.SEARCH_COMPLETE:
case collection.LOAD_SUCCESS: {
const books = action.payload;
const newBooks = books.filter(book => !state.entities[book.id]);
const newBookIds = newBooks.map(book => book.id);
const newBookEntities = newBooks.reduce((entities: { [id: string]: Book }, book: Book) => {
return Object.assign(entities, {
[book.id]: book
});
}, {});
return {
ids: [ ...state.ids, ...newBookIds ],
entities: Object.assign({}, state.entities, newBookEntities),
selectedBookId: state.selectedBookId
};
}
case book.LOAD: {
const book = action.payload;
if (state.ids.indexOf(book.id) > -1) {
return state;
}
return {
ids: [ ...state.ids, book.id ],
entities: Object.assign({}, state.entities, {
[book.id]: book
}),
selectedBookId: state.selectedBookId
};
}
case book.SELECT: {
return {
ids: state.ids,
entities: state.entities,
selectedBookId: action.payload
};
}
default: {
return state;
}
}
}