【发布时间】:2017-06-03 01:18:33
【问题描述】:
我已经启动并运行了 ngrx/store,我正在考虑它。我可以创建一个动作和一个 reducer 来存储基于模型的数据,但是当我创建一个内部状态的第二个实例时,它只是在我现有的状态中添加了一个新行:
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: []
}
}]
}
我已尝试从提供的示例应用程序中进行一些调整,但目前我无法从中提取我需要的内容以找到解决方案,如果有人能够让我知道我的哪一部分代码需要更改才能使其正常工作,那太好了。
我确实在 reducer 开始时尝试过休息状态,但这显然只会在每次调用时将其擦除,从而破坏以前的数据。
更新工作,:
所以我更新了reducer,建议我需要在状态中创建一个空数组,然后修改我的return语句,reducer工作:
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})
}
}
【问题讨论】:
-
您上次 sn-p 中的 JSON 似乎无效。
-
这只是作为一个例子来说明我想要一个状态内的实例订单头数组,我现在已经更新为有效的 json