[英]NGRX Store - Create multiple instance of one model
我已經啟動並運行了 ngrx/store,我正在了解它。 我可以創建一個 action 和一個 reducer 來存儲基於模型的數據,但是當我去創建一個內部狀態的第二個實例時,它只是向我現有的狀態添加一個新行:
減速器.ts
import * as orderhead from '../_actions/orderhead';
import { OrderHead } from '../_models/index';
// Set State to mimic that of the OrderHead model
export interface State {
orderID: string[];
entryDate: string[];
requireDate: string[];
headerRef: string[];
pirotity: string[];
};
// Set initial state to empty
const initialState: State = {
orderID: [],
entryDate: [],
requireDate: [],
headerRef: [],
pirotity: [],
};
export function OHreducer(state = initialState, action: orderhead.Actions): State{
switch (action.type) {
case orderhead.ActionTypes.CREATE_OH:
// Create a new instance of the model OrderHead and store it
// all other aspects of the model will be updated by other actions
const order = [...state.orderID, action.payload.orderID]
return Object.assign({}, state, {orderID: order})
}
}
還有一些代碼來用一些數據填充商店:
createOrderHead(orderid){
this._store.dispatch({type: orderhead.ActionTypes.CREATE_OH, payload: {orderID: orderid} });
}
現在,如果我運行:
createOrderHead('ABC123')
createOrderHead('DEF456')
我得到的是:
{ orderhead: {
orderID: [
'ABC123',
'DEF456'
],
entryDate: [],
requireDate: [],
headerRef: [],
pirotity: []
}
}
但是,我所追求的是:
{ orderhead: [
{
orderID: 'ABC123',
entryDate: [],
requireDate: [],
headerRef: [],
pirotity: []
},
{
orderID: 'DEF456',
entryDate: [],
requireDate: [],
headerRef: [],
pirotity: []
}
}]
}
我試圖從提供的示例應用程序中進行一些調整,但目前我無法從中提取我需要的內容以找到解決方案,如果有人能夠讓我知道我的代碼的哪一部分需要更改以使其正常工作,那將是很棒的。
我確實在減速器開始時嘗試了靜止狀態,但這顯然只是在每次調用時將其擦干凈,破壞了以前的數據。
更新工作,:
所以我更新了我的減速器,建議我需要在 state 中創建一個空數組,然后修改我的 return 語句,工作減速器:
import { OrderHead } from '../_models/index';
// Set state to that of imported model
export interface State {
orders : OrderHead[]
};
// Set initial state to empty
const initialState: State = {
orders : []
};
export function OHreducer(state = initialState, action: orderhead.Actions): State{
switch (action.type) {
case orderhead.ActionTypes.CREATE_OH:
// Map payload to instance of array
const order = [...state.orders, action.payload]
// Assign the order to the array
return Object.assign({}, state, {orders: order})
}
}
我認為您應該需要將您的狀態更改為一系列訂單。 然后將訂單添加到數組中。
import * as orderhead from '../_actions/orderhead';
import { OrderHead } from '../_models/index';
// Set State to mimic that of the OrderHead model
export interface Order {
orderID: string | null;
entryDate: string | null;
requireDate: string | null;
headerRef: string | null;
pirotity: string | null;
}
export interface State {
orders : Order[]
};
// Set initial state to empty
const initialState: State = {
orders : []
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.