我如何在新的reducer中创建数组?
使用旧的语法ID可以做到这一点:
const initialState: Comment = {
fullName: null,
comment: null
};
export function commentReducer(state: Comment[] = [], action: CommentAction.Action) {
switch (action.type) {
case CommentAction.ADD_COMMENT:
return [...state, action.payload];
case CommentAction.REMOVE_COMMENT:
state.splice(action.payload, 1);
return state;
default:
return state;
}
}
现在在新的reducer中,我这样做但不是数组
export const initialState: Comment = {
fullName: null,
comment: 'null'
};
const commentReducer = createReducer(
initialState,
on(CommentAction.addcomment, (state, { fullName, comment }) => ({ fullName, comment }))
);
export function reducer(state: Comment | undefined, action: Action) {
return commentReducer(state, action);
}
我尝试调度,但没有将其添加到数组中,只是替换了它。我做错了什么?
答案 0 :(得分:1)
首先:您的initialState应该是一个数组,其次:仅返回一个数组
export const initialStat: Comment[] = [];
const commentReducer = createReducer(
initialState,
on(CommentAction.addcomment, (state, { fullName, comment }) => [...state, { fullName, comment }])
);
export function reducer(state: Comment[], action: Action) {
return commentReducer(state, action);
}
我还在需要的地方将注释类型更改为Comment []