我正在尝试将一个数组添加到我的存储中,但是在tasks: payload.payload ? [ ...state, payload.payload ] : []
,Error:(22, 35) TS2461: Type 'ITask' is not an array type
处始终遇到以下错误。我该如何解决?
import * as TaskActions from './task.actions';
import { Action, createReducer, on } from '@ngrx/store';
import { ITask } from '../../models/task';
export interface State {
task: ITask | null;
error: any;
}
const initialState: ITask = {
basketTotal: 0,
carePlanPrice: 0,
category: null,
completionDate: null
};
export const taskReducer = createReducer(
initialState,
on(TaskActions.getData, state => ({ ...state })),
on(TaskActions.dataReceived, (state, payload) => ({
...state,
tasks: payload.payload ? [ ...state, payload.payload ] : []
})),
on(TaskActions.dataNotReceived, state => ({ ...state })),
on(TaskActions.signOut, state => ({ ...state })),
on(TaskActions.signOutSuccess, state => ({ ...state, ...initialState })),
);
export function reducer(state: ITask | undefined, action: Action) {
return taskReducer(state, action);
}
屏幕截图:
答案 0 :(得分:1)
splice
,Task
不是数组。因此,无需使用payload
运算符。
spread
扩展语法允许迭代,例如数组表达式或 字符串,以将其扩展为零个或多个参数(用于函数) 调用)或元素(用于数组文字)或对象 将表达式扩展到零个或多个键值对的地方 (用于对象文字)。
如果要将它们添加为对象:
tasks: payload.payload ? [ state, payload.payload ] : []
答案 1 :(得分:0)
您需要像这样更改代码
const initialState: State = {
//set default initial state inside
};
为InitialState而不是ITask使用State接口
由于您的界面只有2个属性
task: ITask | null;
error: any;
所以您的initialState将是
const initialState: State = {
task: null,
error: null
};
还有你的减速器
on(TaskActions.dataReceived, (state, payload) => ({
...state,
task: payload.payload ? [ ...state, payload.payload ] : []
})),