数据更新中未定义还原器返回



我试图创建一个reducer来在调用操作后删除对象,但我无法在数据中更新和保存新对象

减速器:

export default function deleteCard(state = INITIAL_STATE, action: any) {
if (action.type === 'DELETE_CARD') {
return state.data.filter((card: Card) => card.cardId !== action.id)
} else {
return state
}
}

操作删除卡

export const deleteCardAction = (id: number) => {
return {
type: 'DELETE_CARD',
id: id
}
}

函数handleDeleteCard((<-调用行动

const cards = useSelector((state: RootStateOrAny) => state.createCard.data);
const dispatch = useDispatch();
function handleDeleteCard() {
cards.map(({ cardId }: Card) => {     
if (cardId === props.activeCard ) {
dispatch(deleteCardAction(cardId))
}
})
}

Initial State:

export const INITIAL_STATE = {
activeCard: 0,
data: [
{
cardId: 0,
cardName: 'Credit card',
cardUsername: 'Vanzo',
cardNumber: '1234 1234 1234 1234',
hideCardNumber: false,
},
]
}

尝试更新时出现以下错误:

TypeError: undefined is not an object (evaluating 'state.data.filter')  

为了更新状态,您需要从reducer返回整个状态,如下所示:

export default function deleteCard(state = INITIAL_STATE, action: any) {
if (action.type === 'DELETE_CARD') {
return {
...state,
data: state.data.filter((card: Card) => card.cardId !== action.id)
}
} else {
return state
}
}

相关内容

  • 没有找到相关文章

最新更新