createReducer()NgRx函数中出现“类型上不存在属性'action'...”错误

时间:2019-09-05 10:14:44

标签: angular typescript ngrx ngrx-reducers

我正在重构NgRx减速器以使用createReducer()函数而不是传统的switch语句,但是出现以下错误:

ERROR in src/app/store/price.reducer.ts(17,32): error TS2339: Property 'action' does not exist on type 'IUser & TypedAction<"[Websocket Service] Get User"> & { type: "[Websocket Service] Get User"; }'.
    src/app/store/price.reducer.ts(18,34): error TS2339: Property 'action' does not exist on type 'IPrice & TypedAction<"[Websocket Service] New Prices"> & { type: "[Websocket Service] New Prices"; }'.

这是我的createReducer()函数和导出的reducer本身:

const userPriceReducer = createReducer(
  defaultState,
  on(actions.getUser, (state, {action}) => ({ ...state, user: { firstName: <string>action.firstName, lastName: <string>action.lastName, age: <number>action.age } })),
  on(actions.newPrices, (state, {action}) => ({ ...state, prices: { ...state.prices, ...{[action.product_id]: <number>action.price } } }))
)

export function reducer(state: State | undefined, action: Action) {
  return userPriceReducer(state, action);
}

这是我的动作:

export const NEW_PRICES = '[Websocket Service] New Prices';
export const GET_USER = '[Websocket Service] Get User';

export const newPrices = createAction(
  NEW_PRICES,
  props<IPrice>()
);

export const getUser = createAction(
  GET_USER,
  props<IUser>()
);

IPriceIUser是描述动作数据形状的界面。

我已经阅读过的文档说,state函数(我放在createReducer()中){action}之后的大括号内的第二个参数应该是是动作的有效负载,但是由于我在动作中使用createAction(),因此动作中没有实际的payload属性,并且动作本身携带数据。使用switch语句方法时,我可以轻松访问和保存此数据。我在这里做什么错了?

1 个答案:

答案 0 :(得分:2)

您的操作没有操作属性,应该是

const userPriceReducer = createReducer(
  defaultState,
  on(actions.getUser, (state, action) => ({ ...state, user: { firstName: <string>action.firstName, lastName: <string>action.lastName, age: <number>action.age } })),
  on(actions.newPrices, (state, action) => ({ ...state, prices: { ...state.prices, ...{[action.product_id]: <number>action.price } } }))
)

或:

const userPriceReducer = createReducer(
  defaultState,
  on(actions.getUser, (state, {firstName,lastName,age}) => ({ ...state, user: { firstName: <string>firstName, lastName: <string>lastName, age: <number>age } })),
  on(actions.newPrices, (state, {price}) => ({ ...state, prices: { ...state.prices, ...{[action.product_id]: <number>price } } }))
)