从 ngrx/store 中提取特定数据

Extracting specific data from ngrx/store

所以我读了this post several times, but the defined setup and examples now differ from the methods shown in the store example app

我已经编写了我的商店代码,主要基于示例应用程序,所以如果我们在本文中继续使用示例应用程序作为参考 post:

书籍缩减器:

export interface State {
  ids: string[];
  entities: { [id: string]: Book };
  selectedBookId: string | null;
};

const initialState: State = {
  ids: [],
  entities: {},
  selectedBookId: null,
};

export function reducer(state = initialState, action: book.Actions | collection.Actions): State {
  switch (action.type) {
    case book.ActionTypes.SEARCH_COMPLETE:
    case collection.ActionTypes.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
      };
    }

export const getEntities = (state: State) => state.entities;
export const getIds = (state: State) => state.ids;

Reducers index.ts(缩短但保留相关信息):

import { createSelector } from 'reselect';
import { compose } from '@ngrx/core/compose';
import { storeFreeze } from 'ngrx-store-freeze';
import { combineReducers } from '@ngrx/store';
import * as fromBooks from './books';


export interface State {
  books: fromBooks.State;
}

const reducers = {
  books: fromBooks.reducer,
};

const productionReducer: ActionReducer<State> = combineReducers(reducers);
export function reducer(state: any, action: any) {
    return productionReducer(state, action);

}

export const getBooksState = (state: State) => state.books;
export const getBookEntities = createSelector(getBooksState, fromBooks.getEntities);
export const getBookIds = createSelector(getBooksState, fromBooks.getIds);

现在我不太明白 "query's" 是如何构建的,我想做的是将 ID 说“456”传递给一个函数,该函数将从ID为“456”的书。 Return 将这些数据放入 Book 的可观察对象中,这样我就可以在我的 template/component 中使用它。

我已经看了几个小时的示例代码,就在我认为我已经掌握了它的时候,我无法弄清楚我做错了什么。如果有人能够解释如何构建采用自定义参数的选择器。

我使用了示例应用程序中的确切代码,希望如果找到答案,会对未来的读者有所帮助。

当您使用 redux 模式时,您必须通过 Actions 完成所有操作。

首先 您需要将选定的 ID 存储在您的商店中,在这种情况下是 "selectedBookId" 属性作为新的操作,例如 SELECTED_BOOK

其次 要获取所选图书,您需要创建一个选择器,将 selectedBookId 与您的实体数组结合起来,例如:

export const getSelected = createSelector(
  getEntities,
  getSelectedId,
  (entities , selectedId) => entities.find(entities => entities.id === selectedId)
);

index.ts

export const getSelectedBook = createSelector(getBookState, fromBook.getSelected);

最后 获取您需要调用选择器的图书对象

this.book$ = this.store.select(fromRoot.getSelectedBook);