gpt4 book ai didi

angular - 从 ngrx/store 中提取特定数据

转载 作者:行者123 更新时间:2023-12-02 07:22:29 25 4
gpt4 key购买 nike

所以我已经多次阅读 this 帖子,但定义的设置和示例现在与 store example app 中显示的方法不同。

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

书籍缩减器:

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);

现在我不太明白“查询”是如何构建的,我想做的是将一个 ID 说“456”传递给一个函数,该函数将在 State 中查看 id 为“456"。将此数据返回到 Book 的可观察对象中,这样我就可以在我的模板/组件中使用它。

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

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

最佳答案

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

首先您需要将选定的 ID 存储在您的 Store 中,在这种情况下是“selectedBookId”属性作为一个新的 Action,如 SELECTED_BOOK

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

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

索引.ts

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

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

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

关于angular - 从 ngrx/store 中提取特定数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41898827/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com