我正在通过将ID传递到后端来删除邀请,这有效。但是,我的reducer无法正常重新呈现新的,已过滤的邀请数组。刷新页面时,删除的邀请消失了。我做错了什么?
行动:
export function deleteInvitation(id) {
const user = JSON.parse(localStorage.getItem('user'));
console.log('now deleting id ', id);
return function(dispatch) {
axios
.delete(`${ROOT_URL}/invitation/`, {
headers: { authorization: user.token },
params: { id: id }
})
.then(response => {
console.log(id);
dispatch({
type: DELETE_INVITATION,
id
});
});
};
}
减速器:
export default function(state = {}, action) {
switch (action.type) {
case INVITATION_SUCCESS:
return { ...state, invited: true, error: {} };
case INVITATION_FAILURE:
return { ...state, invited: false, error: { invited: action.payload } };
case FETCH_INVITATIONS:
return { ...state, invitations: action.payload };
case DELETE_INVITATION:
return {
...state,
invitations: state.invitations.filter(_id => _id !== action.id)
};
default:
return state;
}
}
答案 0 :(得分:1)
我正在猜测invitations
数组的结构......
在reducer中,过滤器功能似乎不正确。该操作正在传递id
属性,我猜测该属性是invitation
对象的属性。但是过滤器功能是从state.invitations
过滤对象,其中对象是id
。也就是说,reducer正在做这样的事情:
const action = {id: 0}
const invitation = [{
_id: 0,
name: 'Name 0',
location: 'Location 0'
},
{
_id: 1,
name: 'Name 1',
location: 'Location 1'
},
{
_id: 2,
name: 'Name 2',
location: 'Location 2'
}
];
console.log(invitation.filter(_id => _id !== action.id));
将返回完整的原始数组,因为过滤器函数正在检查action.id
(一个数字)与invitation
(一个对象)的不等式。基本上是:
{
_id: 0,
name: 'Name 0', !=== number
location: 'Location 0'
}
对于任何num
和/或任何invitation
对象,将返回true,因此过滤器函数将返回state.invitations
中的每个项目。
要解决此问题,请针对invitation._id
检查action.id
,如下所示:
const action = {id: 0}
const invitation = [{
_id: 0,
name: 'Name 0',
location: 'Location 0'
},
{
_id: 1,
name: 'Name 1',
location: 'Location 1'
},
{
_id: 2,
name: 'Name 2',
location: 'Location 2'
}
];
console.log(invitation.filter(invitation => invitation._id !== action.id));